Mid-level (2-5 years)JavaScript

What is prototypal inheritance in JavaScript?

Quick answer

In JavaScript every object has an internal link to another object called its prototype, and property lookups walk up this prototype chain until the property is found or the chain ends.

When you read obj.name, the engine checks obj first, then obj's prototype, then that object's prototype, and so on until it reaches null. Methods shared by all instances live on the prototype instead of being copied onto each object, which saves memory.

The class keyword is syntax over this mechanism. class B extends A sets up B.prototype to inherit from A.prototype. You can create an object with a chosen prototype using Object.create(proto), and inspect it with Object.getPrototypeOf(obj).

const animal = { speak() { return this.name + " makes a sound"; } };
const dog = Object.create(animal);
dog.name = "Rex";
dog.speak();                              // "Rex makes a sound"
Object.getPrototypeOf(dog) === animal;    // true

class Cat {
  constructor(name) { this.name = name; }
  speak() { return this.name + " meows"; }   // lives on Cat.prototype
}

Key points

  • Lookups follow the prototype chain
  • class is syntactic sugar over prototypes
  • Shared methods live on the prototype, not on each instance