In JavaScript, a constructor is a special function used to create and initialize objects.
Simple idea
A constructor is like a blueprint for creating multiple similar objects.
- Constructor function (old/classic way):
function Person(name, age) {
this.name = name;
this.age = age;
}
const p1 = new Person("Praveen", 25);
const p2 = new Person("Kumar", 30);
console.log(p1.name); // Praveen
Key points:
The function name usually starts with a capital letter.
The new keyword is used to call the constructor.
this refers to the new object being created.
- Constructor in ES6 class (modern way):
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const p1 = new Person("Praveen", 22);
Here:
constructor() is a special method inside a class.
It runs automatically when you create an object with new.
What happens when you use new?
When you do:
const p = new Person("Praveen", 22);
JavaScript:
Creates a new empty object
Sets this to that object
Runs the constructor function
Returns the object.
(TBD)
pop()
shift()
unshift()
forEach()
map()
filter()
reduce()
find()
findIndex()
Top comments (0)