liveBook · Manning

Prototype chain

As explained in Secrets of the JavaScript Ninja, Third Edition

The linked sequence of prototype objects used for JavaScript inheritance and property lookup.

When an object lacks a requested property, JavaScript searches its prototype for it. If that object lacks the property too, the search continues up the prototype chain until it finds the property or reaches the end. Data properties and methods can both be inherited. section 9.3.1

Use `Object.setPrototypeOf(object, prototype)` to set an object’s prototype. The `in` operator checks whether a property is accessible, including through the chain. Prototypes form a linear chain: each prototype has at most one prototype. section 9.3.1 section 9.4.2

Listing 9.4 With prototypes, objects can fall back on other objects
const yoshi = { skulk: true }; #A
const hattori = { sneak: true }; #A
const kuma = { creep: true }; #A
 
console.assert("skulk" in yoshi, "Yoshi can skulk");
console.assert(!("sneak" in yoshi), "Yoshi cannot sneak");
console.assert(!("creep" in yoshi), "Yoshi cannot creep");
 
Object.setPrototypeOf(yoshi, hattori); #B

console.assert("sneak" in yoshi, "Yoshi can now sneak"); #C
console.assert(
  !("creep" in hattori),
  "Hattori cannot creep",
);

Object.setPrototypeOf(hattori, kuma);
console.assert("creep" in hattori, "Hattori can now creep"); #D
console.assert("creep" in yoshi, "Yoshi can also creep"); #D

Trace how `yoshi` gains access to properties on `hattori` and then `kuma` through successive prototype links. section 9.3.1

JavaScript classes provide syntax for this same mechanism: instance methods are inherited through prototypes, and `extends` links a child class to a parent. `super` accesses the parent class; `instanceof` checks whether a function’s prototype appears in an object’s chain. section 9.4.1 section 9.4.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Traces lookup through successive prototypes and connects the mechanism to class inheritance.
Examples
Demonstrates skulk, sneak, and creep lookup across three objects and inherited methods across Person and Ninja.
What you can do after
Understand property access by tracing own properties and fallback lookup through a prototype chain.
How it connects
Connects property lookup with constructors, classes, extends, super, and instanceof.

Also explained in

Compare how 3 books explain prototype chain →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.