Constructors in JavaScript are special functions designed to initialize objects. They are invoked with the new keyword and are responsible for setting up the initial state (properties) and behavior (methods) of newly created objects. Conventionally, constructors start with an uppercase letter to distinguish them from regular functions.
function ConstructorName(parameter1, parameter2, ...) {
this.property1 = parameter1;
this.property2 = parameter2;
// Other property assignments
this.methodName = function() {
// Method implementation
};
}
// Optionally, add methods to the prototype
ConstructorName.prototype.methodName = function() {
// Method implementation
};
// Constructor function for creating Car objects
function Car(make, model) {
this.make = make; // Initialize the 'make' property
this.model = model; // Initialize the 'model' property
// Method defined inside the constructor
this.drive = function() {
return "Driving a " + this.make + " " + this.model + ".";
};
}
// Creating instances of Car using the constructor
let car1 = new Car( "Renault","Kwid");
let car2 = new Car("Honda", "Accord");
// Calling the drive method on instances
console.log(car1.drive()); // Output: Driving a Toyota Camry.
console.log(car2.drive()); // Output: Driving a Honda Accord.