Constructor
A constructor is a special function/method used to initialize an object when it is created.
Function Constructor
A function constructor is a normal function used with the newkeyword to create and initialize objects.
Example
function Student(name, age) {
this.name = name;
this.age = age;
}
const s1 = new Student("Divya", 20);
const s2 = new Student("Aruna", 22);
console.log(s1.name); // Divya
console.log(s2.age); // 22
Keywords Points
- Function name usually starts with a capital letter
- new keyword is mandatory
- this refers to the new object
How it Works
const user = new Person("Divya", 22);
- Creates an empty object {}
- Sets this to that object
- Assigns values (this.name, this.age)
- Returns the object
Constructor in Class
A constructor is a method inside a class that:
- Runs automatically when an object is created
- Is used to set initial values (properties)
Example
class Person {
constructor(name, age) {
this.name = name; // assign value
this.age = age;
}
}
const p1 = new Person("Divya", 22);
console.log(p1.name); // Divya
console.log(p1.age); // 22
How it works (Step-by-step)
- new Person("Divya", 22) is called
- A new empty object is created
- constructor() runs automatically
- this.name = "Divya"
- this.age = 22
- Object is returned
Top comments (0)