Prototypal Inheritance
In JavaScript, objects inherit directly from other objects, unlike classical inheritance in other languages.
🧠Main idea:
Every JavaScript object has a hidden internal property called [[Prototype]] (or proto in some cases). This prototype is simply another object.
When you try to access a property or method on an object:
- If the object does not have it, JavaScript looks up the prototype chain — i.e., it checks the object's prototype, and so on.
Simple Example:
Here, child itself doesn’t have greet(), but JavaScript looks up child.proto (which is parent) and finds greet() there.
The Prototype Chain (visual):
It's like a linked list! When JavaScript can't find a property, it moves up the chain until it finds it or reaches null.
Why is it powerful?
- You can share methods across multiple objects without copying.
- It's memory efficient: shared behavior lives once on the prototype, not on each object.
Modern JavaScript and class syntax:
dog internally has a prototype pointing to Animal.prototype.
In short: Prototypes are the "behind-the-scenes" mechanism for inheritance in JavaScript — flexible, dynamic, and powerful.