Curriculum
Module 21 // Core JavaScript
Constructor Functions & new
Module Objective
new operator steps, instance creation, constructor behavior
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Prototype Methods (Memory Safe)
function Car(make) {
this.make = make;
}
// Add method to prototype, not every instance
Car.prototype.start = function() {
console.log(this.make + " is starting...");
};
const myCar = new Car("Toyota");
myCar.start();💡 Defining methods inside the constructor (using `this.start = ...`) creates a new function for every object. Putting them on the `.prototype` stores the function only once in memory, which is much more efficient.
// Example 2
// 2. The 'new' keyword steps
// When you run: new User("Subhajit")
// 1. A new empty object is created {}
// 2. [[Prototype]] is linked to User.prototype
// 3. 'this' is bound to the new object
// 4. The function executes
// 5. The object is returned💡 The `new` keyword does a lot of work under the hood to ensure the object is properly linked and initialized.
// Example 3
// 3. Forgetting 'new' (Danger!)
function Person(name) {
this.name = name;
}
// const bob = Person("Bob");
// console.log(window.name); // "Bob" (Leaked to global!)💡 If you forget `new`, `this` points to the global object (or `undefined` in strict mode), causing bugs and
Engine & Memory Architecture
Allocation & Linking
1. The 'prototype' Property:
- Every function has a
.prototypeobject created automatically in the Heap. - This object holds the shared methods for all instances created by that constructor.
2. Instance Linking:
- When
newis called, the engine allocates space in the Heap for the new instance. - It adds a hidden [[Prototype]] pointer from the instance back to the constructor's
prototypeobject.
3. Reference Overhead:
- Instance properties (e.g.,
this.name) are stored on the object in memory. - Prototype methods are stored externally and accessed via a pointer.
- Hardware: This approach balances fast access (for local properties) with low memory usage (for shared methods).