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 Bob

When 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 FunctionFactory Function
Uses new keywordReturns object manually
Uses thisDoesn't use this
Harder to test/mockMore 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.” 🏭