Chapter XIX · Prototypes
Constructor Functions
A constructor function is a regular function used with the `new` keyword to create and initialize object instances.
01 How It Works
Think of a factory production mold stamping out consistent product units.
When invoked with `new`, the engine creates a new blank object, binds `this` to it, links its prototype, and returns the object automatically.
example.js
function User(name) {
this.name = name;
}
const user1 = new User("Alice");
1. Define a function with capitalized naming conventions.
2. Invoke the function using the `new` operator.
3. Assign properties to `this` inside the constructor body.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
function Car(brand) {
this.brand = brand;
}
const myCar = new Car("Toyota");
Key Takeaway
Constructor functions serve as object blueprints before ES6 class syntax was introduced.