Constructor in JavaScript

In JavaScript, a constructor is a special function that is used to create and initialize objects. It is typically defined as a method within a class or a function, and it is called using the new keyword.

What happens when a constructor gets called?

In JavaScript, here's what happens when a constructor is invoked:

  • A new empty object is created
  • this keyword starts referring to that newly created object and hence it becomes the current instance object
  • The newly created object is then returned as the constructor's returned value

Here's an example of a constructor function in JavaScript:

function Person(name, age)
{
    this.name = name;
    this.age = age;
}
// Creating objects using the constructor function
var person1 = new Person("John", 25);
var person2 = new Person("Jane", 30);
console.log(person1.name); // Output: John
console.log(person2.age); // Output: 30

In the example above, Person is a constructor function for creating Person objects. It takes two parameters, name and age, and assigns them to the respective properties of the newly created object using this keyword.

When you use the new keyword followed by the constructor function (new Person(...)), it creates a new object and calls the constructor function with the provided arguments. The newly created object is then assigned to the variable (person1 and person2 in the example) for further use.

Conclusion

By convention, constructor functions in JavaScript are named with an initial capital letter to distinguish them from regular functions. This helps indicate that they should be called with the new keyword. Let's read about encapsulation in JavaScript in the next module.


Learn via Video Course

Javascript(English) Logo

Javascript(English)

72966

3 hrs