Topic 30 of 37
Prototypal Linkage
Overview
Unlike languages with classical inheritance (Java, C++), JavaScript uses Prototypal Inheritance. Every object in JS has a hidden property (accessed via __proto__ or Object.getPrototypeOf) that points to another object, its Prototype. When you access a property, JS looks at the object; if it's not there, it looks at the prototype, and so on up the Prototype Chain.
Syntax
All objects ultimately inherit from Object.prototype.
The Prototype Chain
javascript
const animal = { eats: true };
const rabbit = { jumps: true };
// Setting rabbit's prototype to animal
Object.setPrototypeOf(rabbit, animal);
// Deprecated way: rabbit.__proto__ = animal;
console.log(rabbit.jumps); // true (found on rabbit)
console.log(rabbit.eats); // true (found on animal prototype)
console.log(rabbit.flies); // undefined (reached end of chain: null)Common Pitfalls
- Extending native prototypes (like Array.prototype.myCustomMethod = ...) is considered very bad practice because it can conflict with future JS updates.
Interview Tips
- Explain the difference between `Object.create()` (which creates a new object with a specified prototype) and modifying `__proto__` directly (which is slow and discouraged).
Real-World Example
Built-in Array methods (like map, filter) live on Array.prototype, not on the array instances themselves, saving massive amounts of memory.
example
javascript
const arr = [1, 2, 3];
// arr itself doesn't have a map method.
// JS finds it on Array.prototype.map