liveBook · Manning

Prototype chain

As explained in Secrets of the JavaScript Ninja, Second Edition

The linked sequence of prototype objects consulted during inherited property lookup.

When an object lacks a requested property, JavaScript can continue the search through its prototype and that prototype’s prototype. This linked sequence is the prototype chain. section 7.5

The chain makes inherited access different from copying:

  • Setting a Ninja prototype to a Person instance links their prototypes, giving Ninja instances access to properties such as Person’s dance method. section 7.3
  • instanceof checks whether the right-side function’s prototype occurs in the left-side object’s chain. Changing that function’s prototype can change the result. section 7.3.2
Listing 7.8. Achieving inheritance with prototypes
function Person(){}
Person.prototype.dance = function(){};

function Ninja(){}
Ninja.prototype = new Person();                             #A

const ninja = new Ninja();
assert(ninja instanceof Ninja,
      "ninja receives functionality from the Ninja prototype");
assert(ninja instanceof Person, "... and the Person prototype");
assert(ninja instanceof Object, "... and the Object prototype");
assert(typeof ninja.dance === "function", "... and can dance!")

Trace how assigning a Person instance as Ninja.prototype lets a Ninja instance pass both instanceof checks and call dance. section 7.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains prototype linking through constructor functions and instanceof checks, including how changing a function’s prototype affects results.
Examples
Uses Person and Ninja constructors, a dance method, and instanceof checks to demonstrate prototype inheritance.
What it assumes
Explains constructor-created objects and prototype references from their setup, without requiring a true class definition.
What you can do after
Evaluate inherited access and instanceof results by tracing an object’s prototype chain.
How it connects
Connects JavaScript objects, constructor functions, inheritance, and the instanceof operator.

Related concepts

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