A constructor function in JavaScript is a special type of function used to create and initialize objects. It acts like a blueprint for creating multiple instances of similar objects.
Key Features:
-
Constructor functions start with a capital letter by convention (e.g., Person, Car).
-
Used with the new keyword to create new object instances.
-
this refers to the new object being created.
Basic Syntax:
function ConstructorName(parameters) {
this.property1 = value1;
this.property2 = value2;
// ...
}
Example: Person Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name);
};
}
// Creating instances
let person1 = new Person("Alice", 25);
let person2 = new Person("Bob", 30);
person1.greet(); // Hello, my name is Alice
person2.greet(); // Hello, my name is Bob
Explanation:
Why Use Constructor Functions?