Constructor Functions in JavaScript
📌 What Are Constructor Functions?
In JavaScript, a constructor function is a special type of function used to create and initialize objects. It acts as a blueprint for creating multiple instances of similar objects. 🧱
Note
Constructor functions are typically capitalized by convention (e.g., Person).
🧪 Basic Syntax
Constructor Function Example
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function () {
console.log("Hi, my name is " + this.name);
};
}
const user1 = new Person("Alice", 25);
const user2 = new Person("Bob", 30);
user1.sayHello(); // Hi, my name is Alice
user2.sayHello(); // Hi, my name is BobWhen the new keyword is used with a constructor function, JavaScript does a few things under the hood:
- Creates a new empty object
- Sets this to point to that object
- Attaches properties/methods from the constructor to the new object
- Returns the object automatically (unless explicitly returned)
💡 Why Use Constructors?
They're useful for creating many similar objects efficiently without repeating code. Ideal for creating instances of a class-like structure before ES6 class syntax existed.
🧠 Adding Methods to Prototype
Prototype Method
Person.prototype.sayAge = function () {
console.log("I am " + this.age + " years old.");
};
user1.sayAge(); // I am 25 years old.Using prototype ensures that all object instances share the same method, saving memory. 🔁
⚠️ Don't Forget new
Note
If you forget the new keyword, this will refer to the global object (or undefined in strict mode), causing unexpected bugs.
Incorrect Usage Without new
const user = Person("Charlie", 40); // ❌ No 'new'
console.log(user); // undefined🔥 Constructor vs. Factory Function
| Constructor Function | Factory Function |
|---|---|
| Uses new keyword | Returns object manually |
| Uses this | Doesn't use this |
| Harder to test/mock | More flexible |
✅ Summary
- Constructor functions are blueprints for object creation
- Use new to instantiate objects
- Methods can be added directly or via prototype
- Common naming convention: capitalize the constructor name
- Useful before ES6 class was introduced
📚 References
>>“Think of constructor functions as factories that mass-produce similar objects with unique identities.” 🏭