Prototypal Inheritance

In JavaScript, inheritance is not class-based as it is in Java or C++. Instead, it is Prototype-based. Objects can inherit properties and methods directly from other objects through an internal link known as the Prototype Chain.


1. The Prototype Chain ([[Prototype]])

Every object in JavaScript has a hidden property called [[Prototype]] (exposed in most browsers as __proto__).

This process is called Property Delegation.


2. .prototype vs. __proto__

A common point of confusion:

function Person(name) { this.name = name; }
const alice = new Person("Alice");

console.log(alice.__proto__ === Person.prototype); // true

3. Method Sharing and Memory

The primary benefit of prototypes is memory efficiency.


4. Prototypal vs. Classical Inheritance


Interview Pro-Tips: How does new work?

If an interviewer asks what happens when you call new Constructor():

  1. A new, empty object {} is created.
  2. The object's __proto__ is linked to Constructor.prototype.
  3. The Constructor is called with this bound to the new object.
  4. The new object is returned (unless the constructor returns a different object).

Technical Summary

  1. Delegation: Looking up properties in a parent object.
  2. Live Links: Prototypes provide a dynamic relationship between instances and their parents.
  3. Shadowing: Defining a property on an instance "Masks" the property on the prototype.