| chapter | 9 |
|---|---|
| description | Understanding Constructor Functions in JavaScript. |
Constructor functions in JavaScript are special functions used to create and initialize objects. They provide a way to define a blueprint for creating multiple objects with similar properties and methods.
A constructor function is defined like a regular function but is typically named with an initial capital letter to distinguish it from regular functions.
Here's a basic example of a constructor function:
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const person1 = new Person("John", "Doe");
const person2 = new Person("Jane", "Smith");
console.log(person1.firstName); // Output: John
console.log(person2.lastName); // Output: SmithIn this example, the Person constructor function initializes the firstName and lastName properties for each new object created.
You can add methods to the objects created by a constructor function by defining them on the constructor's prototype.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
};
const person1 = new Person("John", "Doe");
console.log(person1.getFullName()); // Output: John DoeThe new keyword is used to create an instance of an object from a constructor function. It performs the following steps:
- Creates a new empty object.
- Sets the
thiskeyword to the new object. - Executes the constructor function.
- Returns the new object.
function Car(make, model) {
this.make = make;
this.model = model;
}
const car1 = new Car("Toyota", "Corolla");
console.log(car1.make); // Output: ToyotaES6 introduced the class syntax, which provides a more concise and readable way to define constructor functions and methods.
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const person1 = new Person("John", "Doe");
console.log(person1.getFullName()); // Output: John DoeConstructor functions are a fundamental feature in JavaScript for creating and initializing objects. They allow you to define a blueprint for objects and add methods to their prototype. With the introduction of ES6, the class syntax provides a more modern and readable way to achieve the same functionality.