Constructor functions define how objects are created in JavaScript. Instances of objects with similar properties and methods can be created with regular functions. Objects created by the constructor function will be referenced using the this keyword. By using this.property or this.method, properties and methods are assigned to the object. Objects are created from constructor functions using the new keyword. Using constructor functions, one can create reusable, customizable, and reusable objects.
// Constructor function
function Car() {
this.make = 'Honda',
this.model = 'Civic',
this.year = 2023;
}
// Object Creation
const car1 = new Car();
// Output
console.log(car1.make); // Honda
console.log(car1.model); // Civic
console.log(car1.year); // 2023
In the above code, we define a constructor function named "Car," which sets default values for the property makes, models, and years. A new object car1 is created from the Car constructor using the "new" keyword. Following that, console.log outputs Honda, Civic, and 2023 as car1's make, model, and year properties.
// Constructor function
function Car() {
this.make = 'Honda',
this.model = 'Civic',
this.year = 2023;
this.start = function () {
console.log('Engine Started');
}
}
// Object Creation
const car1 = new Car();
// Output
console.log(car1.make); // Honda
console.log(car1.model); // Civic
console.log(car1.year); // 2023
car1.start(); // Engine Started
// Constructor function with parameters
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.start = function() {
console.log("Engine Started");
};
}
// Object Creation
var car1 = new Car("Honda", "Civic", 2023);
// Output
console.log(car1.make); // Honda
console.log(car1.model); // Civic
console.log(car1.year); // 2023
car1.start(); // Engine Started