A constructor function in JavaScript is a special type of function used to create and initialize objects. Unlike regular functions, constructor functions are intended to be used with the new
keyword, which creates a new instance of the object and sets up its properties and methods.
Here's an example of a constructor function:
// Constructor function to create Person objects
function Person(firstName, lastName, age, isMarried) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.isMarried = isMarried;
this.fullName = function() {
return `${this.firstName} ${this.lastName}`;
};
this.celebrateBirthday = function() {
this.age += 1;
console.log(`Happy Birthday ${this.firstName}! You are now ${this.age} years old.`);
};
}
// Using the constructor function to create new Person objects
const person1 = new Person('John', 'Doe', 30, false);
const person2 = new Person('Jane', 'Smith', 25, true);
console.log(person1.fullName()); // Output: John Doe
console.log(person2.fullName()); // Output: Jane Smith
person1.celebrateBirthday(); // Output: Happy Birthday John! You are now 31 years old.
person2.celebrateBirthday(); // Output: Happy Birthday Jane! You are now 26 years old.
Instance Creation:
Prototypal Inheritance:
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// Adding a method to the prototype
Person.prototype.fullName = function() {
return `${this.firstName} ${this.lastName}`;
};
const person1 = new Person('John', 'Doe', 30);
const person2 = new Person('Jane', 'Smith', 25);
console.log(person1.fullName()); // Output: John Doe
console.log(person2.fullName()); // Output: Jane Smith
Automatic Property Initialization:
new
keyword automates the process of property initialization, setting this
to the new object and returning it. Regular functions do not automatically create a new object context.function createPerson(firstName, lastName, age) {
return {
firstName,
lastName,
age,
fullName() {
return `${firstName} ${lastName}`;
}
};
}
const person1 = createPerson('John', 'Doe', 30);
const person2 = createPerson('Jane', 'Smith', 25);
console.log(person1.fullName()); // Output: John Doe
console.log(person2.fullName()); // Output: Jane Smith
Code Organization and Readability:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Car.prototype.getCarInfo = function() {
return `${this.year} ${this.make} ${this.model}`;
};
const car1 = new Car('Toyota', 'Camry', 2020);
const car2 = new Car('Honda', 'Civic', 2019);
console.log(car1.getCarInfo()); // Output: 2020 Toyota Camry
console.log(car2.getCarInfo()); // Output: 2019 Honda Civic
Encapsulation and Reusability:
function BankAccount(owner, balance) {
this.owner = owner;
this.balance = balance;
}
BankAccount.prototype.deposit = function(amount) {
this.balance += amount;
console.log(`${amount} deposited. New balance: ${this.balance}`);
};
BankAccount.prototype.withdraw = function(amount) {
if (amount <= this.balance) {
this.balance -= amount;
console.log(`${amount} withdrawn. New balance: ${this.balance}`);
} else {
console.log('Insufficient funds');
}
};
const account1 = new BankAccount('Alice', 1000);
const account2 = new BankAccount('Bob', 500);
account1.deposit(200); // Output: 200 deposited. New balance: 1200
account2.withdraw(100); // Output: 100 withdrawn. New balance: 400
Constructor functions in JavaScript are effective for creating and initializing multiple instances of objects with shared properties and methods. They support prototypal inheritance, automatic property initialization, and encapsulation, making them a powerful tool for organizing and managing code in complex applications.