🏗️ Constructor Functions in JavaScript
Category: js / general-concepts
Difficulty: medium
A constructor in JavaScript is a special function used to create and initialize objects. It allows you to define reusable object structures. 1️⃣ What is a Constructor? A constructor function : Is a regular function but used with the new keyword. Initializes an object and assigns properties to it. Typically follows PascalCase naming convention (Person, Car, Employee). Example of a Constructor Function [code example] 📌 How it works: new Person("Alice", 25) creates a new empty object . this inside Person refers to the newly created object. The function assigns properties (name and age) to this. The new object is returned automatically. 2️⃣ Constructor Without new (Why new is Needed) If you forget to use new, this refers to the global object (window in browsers, global in Node.js). [code example] ✅ Always use new when calling a constructor function. 3️⃣ Constructor with Methods You can add methods inside the constructor, but it's inefficient because each instance gets a new copy of the method. [code example] 4️⃣ Constructor + Prototype (Efficient Approach) Instead of defining methods inside the constructor, use prototype to share methods among all instances. [code example] 📌 Why use prototype? Reduces memory usage by sharing methods among instances. 5️⃣ Constructor in ES6 Classes (Modern Approach) ES6 introduces class syntax, making constructor-based object creation cleaner. [code example] ✅ Same behavior as constructor functions but more readable. ✅ Uses prototype under the hood. 6️⃣ Checking Constructor Reference Each object instance retains a reference to its constructor. [code example] This is why resetting constructor in prototype inheritance is necessary: [code example] 7️⃣ Custom Object Creation Without new You can simulate new by manually creating and returning an object. [code example] 📌 Difference? new is not required. Object literals are used instead of this. 🚀 Summary Constructor Function Function-based newkeyword Inside function (bad) or prototype (good...