1. Constructor:
In JavaScript, a constructor is a special function used to create and initialize objects.
Instead of creating objects again and again manually, constructors help you create multiple objects with the same structure easily.
2. Why Constructor is Needed:
Imagine you want to create multiple students:
let student1 = {
name: "Saha",
age: 21
}
let student2 = {
name: "Priya",
age: 22
}
This works… but it's repetitive and messy.
Instead, use a constructor:
function Student(name, age) {
this.name = name;
this.age = age;
}
let student1 = new Student("Saha", 21);
let student2 = new Student("Priya", 22);
console.log(student1);
console.log(student2);
Now you can create unlimited objects easily.
3. Important Rules of Constructor:
1. Constructor Name Starts with Capital Letter:
function Student() {}
This is not mandatory, but it's a standard practice.
2. Use this Keyword:
this refers to the current object being created.
function Student(name, age) {
this.name = name;
this.age = age;
}
3. Use new Keyword:
Constructor only works when using new
let s1 = new Student("Saha", 21);
Without new, it won't behave like a constructor.
Example:
function Car(brand, price) {
this.brand = brand;
this.price = price;
}
let car1 = new Car("BMW", 5000000);
let car2 = new Car("Audi", 6000000);
console.log(car1);
console.log(car2);
Output:
Car { brand: 'BMW', price: 5000000 }
Car { brand: 'Audi', price: 6000000 }
Top comments (0)