liveBook · Manning

Inheritance

As explained in Secrets of the JavaScript Ninja, Third Edition

Inheritance is the behavior by which a JavaScript object obtains accessible properties from its prototype chain, including both data properties and methods.

Inheritance lets an object access properties it does not own by searching its prototype chain. JavaScript classes provide a familiar syntax for inheritance, but rely on prototypes underneath. section 9.3.1 section 9.0

Keep these mechanics in mind:

  • Property lookup checks the object first, then its prototype and successive prototypes until the search ends. Data properties and methods are inherited alike. section 9.3.1
  • Classes use extends to form a parent-child relationship. A child constructor can call super before using this; static properties are not inherited, and inheritance is linear. section 9.4.2

A property found up the chain

Give yoshi its own skulk property, then set hattori as its prototype. Yoshi can now access hattori’s sneak property; chaining hattori to kuma makes kuma’s creep property accessible through both objects. section 9.3.1

Listing 9.8 A class that inherits from a parent
class Person {
  name: string;
 
  constructor(name: string) {
    this.name = name;
  }
 
  dance() {
    return true;
  }
}
 
class Ninja extends Person { #A
  sneakiness: number;

  constructor(name: string, sneakiness = 3) { #B
    super(name); #B
    this.sneakiness = sneakiness; #B
  } #B

  sneak() {
    return `Sneak level ${this.sneakiness}`;
  }
}

const ninja = new Ninja("Chizu", 5);

console.assert(
  ninja instanceof Ninja,
  "A ninja is a ninja",
);

console.assert(
  ninja instanceof Person,
  "A ninja is also a person",
);

See a Person and Ninja class example using extends, super, and instanceof. section 9.4.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains prototype-chain lookup and class inheritance mechanics, including constructors and super, and notes the absence of multiple inheritance.
Examples
Uses linked Yoshi, Hattori, and Kuma objects, plus Person and Ninja classes.
What you can do after
Apply inheritance with Object.setPrototypeOf or class extends, and check property access with in and instanceof.
How it connects
Connects prototype chains, object properties, constructors, JavaScript classes, and the super keyword.

Also explained in

Compare how 23 books explain inheritance →

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.