JavaScript Constructor Method

The JavaScript Constructor Method is used to create and initialize objects. A constructor method is a special method of a class that is executed when a new instance of the class is created. In JavaScript, constructors are typically defined inside a class or function.

Key Features of Constructor Methods:

Example: Class Constructor

This example demonstrates a class constructor that initializes an object's properties:

Class Constructor Example


class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
            
    greet() {
        return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
    }
}
            
const person1 = new Person("Alice", 25);
document.writeln(person1.greet());
            

Output

Hello, my name is Alice and I am 25 years old.

Explanation of Code:

Example: Function Constructor

This example demonstrates how to use a function as a constructor:

Function Constructor Example


function Car(make, model) {
    this.make = make;
    this.model = model;
    this.getDetails = function() {
        return `${this.make} ${this.model}`;
    };
}
            
const car1 = new Car("Toyota", "Corolla");
document.writeln(car1.getDetails());
            

Output

Toyota Corolla

Explanation of Code:

Advantages of Constructor Methods: