70. Constructor Functions (Legacy OOP)
Before ES6 introduced the class keyword (syntactic sugar), JavaScript used constructor functions to define blueprints for creating multiple objects of the same type.
Defining a Constructor
- The function is named starting with a capital letter (a convention).
- It takes parameters to set initial properties.
- It uses
thisto assign properties to the newly created object.
javascript
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(Hi, I'm ${this.name}.);
};
}
Creating Instances (new Keyword)
To create a new object from this blueprint, we must use the new keyword.
javascript const alice = new Person('Alice', 28); const bob = new Person('Bob', 35);
alice.greet(); // Hi, I'm Alice. console.log(bob.age); // 35
Key: The new keyword automatically creates an empty object, binds this to that object, executes the function, and returns the new object.