Introduction
In JavaScript, a constructor is a special function or method used to create and initialize objects. Whenever you want to create multiple objects with similar structure, constructors help you do it easily and efficiently.
Why Do We Need Constructors?
Without constructors, you would have to manually create objects like this:
let student1 = { name: "Silambu", age: 21 };
let student2 = { name: "sanjay", age: 22 };
This becomes repetitive and messy when creating many objects.
Constructors solve this problem by providing a template (blueprint).
Constructor Using Class (Modern Way)
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let s1 = new Student("Silambu", 21);
console.log(s1);
Output:
{ name: "Silambu", age: 21 }
How It Works Internally
When you write:
let s1 = new Student("Silambu", 21);
JavaScript does the following steps:
- Creates an empty object
{ } - Sets
thisto point to that object - Calls the constructor function
- Assigns values (
name,age) - Returns the object
Concepts
constructor()
- Special method inside a class
- Runs automatically when object is created
this
- Refers to the current object
- Used to assign values
new keyword
- Creates object
- Calls constructor
Constructor Function (Old Way)
Before ES6, constructors were written like this:
function Student(name, age) {
this.name = name;
this.age = age;
}
let s1 = new Student("Silambu", 21);
This still works, but modern JS prefers class syntax.
Top comments (0)