OOP in JavaScript
Constructor Functions & the new Keyword
Master traditional OOP in JavaScript. Learn how constructor functions and the new keyword allocate objects, bind prototypes, and set execution context.
1. Introduction
Before the class keyword was introduced in ES6, JavaScript implemented Object-Oriented Programming (OOP) using Constructor Functions combined with the new keyword to allocate new objects and bind prototype methods.
2. Why It Matters
Under the hood, ES6 classes are syntactic sugar over constructor functions and prototypal inheritance. Understanding the behavior of the new keyword and prototype bindings is key to mastering JavaScript object instantiation and memory management.
3. Real-World Analogy
Think of a Manufacturing Assembly Line:
- The new Keyword (Allocating materials): The start button on the assembly line. It fetches a raw, blank object frame from warehouse inventory and places it on the line.
- The Constructor Function (Assembly workers): Workers who stamp properties on the frame: "Add serial number: A-1", "Add name label: User".
- The Prototype (Shared Blueprints): The instruction manual pinned on the wall. The workers do not copy the manual onto every item; instead, every item references the same instruction manual on the wall (shared memory reference), saving resources.
4. Instantiation Steps
When you call a function using the new keyword, the engine executes four steps:
1. It creates a new, blank plain JavaScript object: {}.
2. It binds the new object's prototype ([[Prototype]]) to the constructor function's prototype property: Constructor.prototype.
3. It calls the constructor function, binding the this context to the newly created object.
4. It returns the new object (unless the constructor returns a custom object reference).
5. Architectural Details
- Prototype Sharing: Placing methods on the prototype (
User.prototype.greet) ensures that only a single instance of the function is created in memory, sharing it across all class instances. Placing methods inside the constructor function creates a new function instance for every object, which consumes more memory. - Implicit Returns: Constructor functions do not need a
returnstatement. The new object is returned automatically. If you return a primitive value (like a string or number), it is ignored; if you return a custom object, that object is returned instead.
6. Practical Example
This script demonstrates creating a constructor function and validating that it was called using the new keyword:
7. Common Mistakes
- Forgetting the new keyword when invoking a constructor function: Without the
newkeyword, the constructor function behaves like a regular function call. Thethiscontext resolves to the global object (windoworundefinedin strict mode), causing properties to leak or throwing a TypeError.
8. Quick Quiz
Q1: What does the new keyword bind the new object's internal [[Prototype]] reference to?
A) The global Object prototype
B) The constructor function's prototype property (Constructor.prototype)
Answer: B — The new keyword binds the new object's internal prototype link directly to the constructor function's prototype property.
9. Scenario-Based Challenge
The Memory-Optimized Shape Factory:
An application allocates 10,000 rectangle objects: { width: 10, height: 20 } inside a simulation. To prevent memory leaks, you must ensure that the calculation method getArea() is shared on the prototype, rather than being re-created inside every object. Write the constructor function and prototype setup.
10. Debugging Exercise
Explain why this constructor function call crashes, and how to fix it:
function Car(model) { this.model = model; }Car.prototype.drive = function() { console.log(`Driving ${this.model}`); };
// Bug: forgot to use the 'new' keyword! const myCar = Car('Tesla'); myCar.drive(); // crashes with TypeError: Cannot read properties of undefined! Why?
View Solution
Diagnosis: Calling Car('Tesla') without the new keyword executes it as a regular function. The function returns undefined because there is no explicit return statement, causing myCar to be undefined.
Fix: Invoke the constructor function using the new keyword to create and return the object instance:
const myCar = new Car('Tesla'); // Works!
myCar.drive(); // "Driving Tesla"
11. Interview Questions
🟢 Q1: Explain the four steps performed by the JavaScript engine when the new keyword is called.
Answer:
1. Object Creation: Creates a new, blank plain JavaScript object: {}.
2. Prototype Binding: Binds the new object's internal prototype ([[Prototype]]) to the constructor function's prototype property: Constructor.prototype.
3. Context Binding: Calls the constructor function, binding the this context to the newly created object.
4. Automatic Return: Returns the new object (unless the constructor explicitly returns a custom object).
12. Production Considerations
- • Transition to ES6 Classes: In modern production code, prefer using the ES6 class syntax instead of writing constructor functions manually. ES6 classes are standard and prevent calling the constructor without the
newkeyword natively.