Curriculum
Module 20 // Core JavaScript
Prototype Chain
Module Objective
Prototypal inheritance, [[Prototype]], Object.create, delegation model
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Sharing Methods
const animal = {
eat() { console.log("Eating..."); }
};
const dog = {
bark() { console.log("Woof!"); }
};
Object.setPrototypeOf(dog, animal);
dog.bark(); // "Woof!"
dog.eat(); // "Eating..." (Inherited)💡 Instead of copying methods to every object (which wastes memory), objects can 'delegate' tasks to their prototypes.
// Example 2
// 2. The Chain End
const obj = {}; // Prototype: Object.prototype
console.log(obj.toString()); // ✅ Works!
console.log(Object.getPrototypeOf(Object.prototype)); // null💡 All objects eventually lead to `Object.prototype`, which is the base of everything. The very end of the chain is `null`.
// Example 3
// 3. Performance Trap
const child = Object.create(null); // No prototype!
// child.toString(); // ❌ Error! (Not a function)
console.log(child); // Truly empty object💡 You can create objects with NO prototype. This is useful for high-performance lookup tables where you don't want collisions with built-in properties like `toString`.
Engine & Memory Architecture
The Chain in Memory
1. Reference Pointers:
- Prototypes are not "copied."
- Each object in the Heap has a small pointer (the [[Prototype]] link) to its parent object in the Heap.
2. Property Lookup (Walking the Chain):
- When you access a property, the CPU doesn't just check one memory address.
- It "walks" the chain: checks Object A → checks Object B → checks Object C.
- Performance: Deep chains (more than 3-4 levels) can noticeably slow down property access.
3. Memory Efficiency:
- By putting methods on the prototype, you store them once in the RAM, even if you have 1,000,000 instances of that object.