The Constructor Method
What is a Constructor?
A constructor() is a special method in a JavaScript class that gets executed automatically the very moment you create a new object using the new keyword.
Its primary job is to initialize the object by setting up its starting properties.
Using the Constructor
Let's say we have a Student class. We want every student to have a unique name and age when they are created. We can pass these values into the constructor.
class Student {
constructor(studentName, studentAge) {
// 'this' refers to the specific object being created right now
this.name = studentName;
this.age = studentAge;
}
introduce() {
console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// The arguments here are passed directly to the constructor
const himanshu = new Student("Himanshu", 22);
const sarah = new Student("Sarah", 25);
himanshu.introduce(); // "Hi, my name is Himanshu and I am 22 years old."
sarah.introduce(); // "Hi, my name is Sarah and I am 25 years old."
The 'this' Keyword inside a Constructor
Inside a constructor, the this keyword is incredibly important. It represents the actual instance (the object) that is currently being created.
When we write this.name = studentName;, we are telling JavaScript: "Take the variable studentName that was passed in, and attach it to this specific object as a property called name."
💡 Himanshu's Tip:
You can only have one constructor method per class in JavaScript. If you try to write two constructor() functions in the same class, JavaScript will throw a SyntaxError. If you need different ways to construct an object, you handle it using default parameters or logic inside that single constructor.
Interview Questions
- When is the
constructormethod called? - What happens if you do not define a constructor in a class?
- What does the
thiskeyword refer to inside a class constructor?