In JavaScript, Constructor is a special method used for creating and initializing objects.
Constructors are typically defined within classes or functions and are used with the new keyword to create instances of objects.
When a constructor is invoked with new, it creates a new object, sets the object's prototype to the constructor's prototype, and executes the constructor function to initialize the object.
function Car(name, year) { this.name = name; this.year = year; this.start = function() { console.log("Starting : " + this.name); }; } // Creating an instance of Car using the constructor const car = new Car("Defender", 2020); // Accessing properties and methods of the instance console.log(car.name); // Outputs: Defender console.log(car.year); // Outputs: 2020 car.start(); // Outputs: Starting : Defender
Car is a constructor function that takes name and year parameters and initializes the properties of the object it creates.
The start method is also defined within the constructor.
A new empty object is created.
The prototype of the new object is set to the constructor's prototype (inherited from Car.prototype).
The constructor function is invoked with this referring to the new object.
Properties and methods are added to the new object based on the constructor's logic.
The new object is returned.
With the introduction of ES6, a more concise syntax for defining classes and constructors was introduced:
class Car { constructor(name, year) { this.name = name; this.year = year; } start() { console.log(`Starting : ${this.name}`); } } // Creating an instance of Car using the class constructor const car = new Car("Defender", 2020); // Accessing properties and methods of the instance console.log(car.name); // Outputs: Defender console.log(car.year); // Outputs: 2020 car.start(); // Outputs: Starting : Defender
the class syntax provides a more structured way to define constructors and methods.
The constructor method is automatically called when an instance is created using new.