DEV Community

Cover image for Level Up Your JS: Constructor Function for Beginners, Explained
Mohammad Aman
Mohammad Aman

Posted on

Level Up Your JS: Constructor Function for Beginners, Explained

Constructor Function

A constructor function in JavaScript is a special type of function used to create and initialize objects. It acts as a blueprint for creating multiple objects with similar properties and methods.

Example:

// Constructor function for creating Person objects
function Person(name, age) {
  // Properties
  this.name = name;
  this.age = age;

  // Method
  this.sayHello = function() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  };
}

// Creating instances of the Person object using the constructor
const person1 = new Person('Mohammad Aman', 22);
const person2 = new Person('Chaimae', 19);

// Accessing properties and calling methods
console.log(person1.name); // Output: Mohammad Aman
person2.sayHello(); // Output: Hello, my name is Chaimae and I'm 19 years old.

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The Person function serves as a constructor for creating Person objects.
  • this refers to the instance of the object being created. Inside the constructor, you attach properties and methods to this.
  • To create an object using the constructor, you use the new keyword followed by the constructor function (new Person()).
  • Each object created with the constructor has its own set of properties and methods.

Key Points:

1. Properties and Methods:

  • Properties are variables that store data within an object.
  • Methods are functions associated with an object.

2. 'this' Keyword:

  • Inside a constructor, 'this' refers to the instance of the object being created.

3. Object Instantiation:

  • Use the 'new' keyword followed by the constructor function to create instances of objects.

4. Reusability:

  • Constructor functions allow you to create multiple instances of objects with shared characteristics.

                           Hope this Helps to you ❤️
Enter fullscreen mode Exit fullscreen mode

Top comments (0)