Curriculum
Concept 56 // Module 06: Objects & Prototypal Inheritance
Constructor Functions & Prototype Methods
Module 06: Objects & Prototypal Inheritance•Concept 56 of 100• 5 min read
Constructor Functions & Prototype Methods
**Constructor Functions** are regular functions used with the **`new`** keyword to create multiple instances of a similar object. They act as blueprints for building objects before the `class` syntax was introduced.
The Core Concept
Syntax Reference
// 1. Definition
function User(name, age) {
// 'this' is automatically created
this.name = name;
this.age = age;
// 'this' is automatically returned
}
// 2. Instance Creation
const user1 = new User("Subhajit", 25);
const user2 = new User("Alex", 30);
Live Interactive Studio
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.
JavaScript Editor
Loading...
Console Output
Waiting for output...
Key Code Patterns in Action
01
Prototype Methods (Memory Safe)
// 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.
02
The 'new' keyword steps
// 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 returnedThe `new` keyword does a lot of work under the hood to ensure the object is properly linked and initialized.
03
Forgetting 'new' (Danger!)
// 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
04
1. Core Usage: Constructor Functions & Prototype Methods
// Core syntax and usage for Constructor Functions & Prototype Methods
const feature = 'constructor-functions-prototype-methods';
console.log('Concept 56:', feature);
console.log('Active:', true);Illustrates the fundamental invocation and syntax structure for Constructor Functions & Prototype Methods.
05
2. Defensive Handling & Edge Case
// Edge-case defensive handling
function handleSafe(input) {
if (input === null || input === undefined) return 'safe-fallback';
return String(input).trim();
}
console.log(handleSafe('constructor-functions-prototype-methods'));
console.log(handleSafe(null));Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with Constructor Functions & Prototype Methods.
06
3. Clean Architecture & Production Pattern
// Production-grade pattern for Constructor Functions & Prototype Methods
const settings = Object.freeze({
id: 'constructor-functions-prototype-methods',
ready: true,
timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);Demonstrates clean, immutable production code avoiding unintended state mutations.
Real-World Engineering Takeaways
Object Blueprints: Creating many users, products, or game entities.
Stateful Logic: Storing data and behavior together in reusable units.
Legacy Codebases: Many older JS libraries (Pre-2015) rely heavily on constructors.
Custom Errors: Extending the built-in `Error` object.
Under the Hood: Engine & Memory Mechanics
How JavaScript Executes This
### **Allocation & Linking**
**1. The 'prototype' Property:**
- Every function has a `.prototype` object created automatically in the **Heap**.
- This object holds the shared methods for all instances created by that constructor.
**2. Instance Linking:**
- When `new` is 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 `prototype` object.
**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).
Quick Knowledge Check
Test your understanding on these 10 questions (one by one):
Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model
What is the core purpose of Constructor Functions & Prototype Methods in JavaScript?
// Concept 56: Constructor Functions & Prototype Methods
// Understanding the core mental model1 / 10