Constructor
Imagine you need to create 100 student objects.Writing each object separately would take a lot of time.Instead, we use a Constructor Function.A constructor acts like a blueprint for creating multiple objects.
Constructor Function
A constructor function starts with a capital letter by convention.It called automatically when object is created
function Student(name, age, course) {
this.name = name;
this.age = age;
this.course = course;
}
Creating Objects Using a Constructor
Use the "new" keyword.
function Student(name, age, course) {
this.name = name;
this.age = age;
this.course = course;
}
let student1 = new Student("Pranay", 21, "ECE");
let student2 = new Student("Rahul", 22, "CSE");
console.log(student1);
console.log(student2);
// Output:
Student { name: 'Pranay', age: 21, course: 'ECE' }
Student { name: 'Rahul', age: 22, course: 'CSE' }
Now we can create as many student objects as we want.
Adding Methods to a Constructor
A constructor can also create methods.
function Student(name, age) {
this.name = name;
this.age = age;
this.greet = function () {
console.log("Hello " + this.name);
};
}
let student = new Student("Pranay", 21);
student.greet();
// Output: Hello Pranay
Why Use Constructors?
Without a constructor:
let student1 = {
name: "Pranay",
age: 21
};
let student2 = {
name: "Rahul",
age: 22
};
let student3 = {
name: "Anu",
age: 20
};
You keep writing the same code.
With a constructor:
function Student(name, age) {
this.name = name;
this.age = age;
}
let student1 = new Student("Pranay", 21);
let student2 = new Student("Rahul", 22);
let student3 = new Student("Anu", 20);
The code becomes shorter and easier to maintain.
Top comments (0)