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:

javascript
1const parent = { 2 greet() { 3 console.log('Hello from parent!'); 4 } 5}; 6 7const child = Object.create(parent); // child inherits from parent 8 9child.greet(); // Output: 'Hello from parent!'

Here, child itself doesn’t have greet(), but JavaScript looks up child.proto (which is parent) and finds greet() there.

The Prototype Chain (visual):

text
1child → parent → Object.prototype → null

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:

javascript
1class Animal { 2 speak() { 3 console.log('Animal speaks'); 4 } 5} 6 7const dog = new Animal(); 8dog.speak(); // Output: 'Animal speaks'

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.