Loading video player…

Follow a Method Up the Chain

In this video, you find out which .describe() the toy library’s shelf loop runs for each kind of toy, and where super.describe() starts looking. You follow each call on the 1,000-brick set up its prototype chain, one link at a time, then do the same for the classes themselves with fromRecord().

Key Points

  • A building set has two links above it. bricks links to BuildingSet.prototype, where the class keeps its methods, and extends links BuildingSet.prototype up to Toy.prototype. .describe() isn’t an own property of bricks, so Object.hasOwn(bricks, "describe") is false.
  • Look on the object first, then take the first match up the chain. bricks.describe() finds the override on BuildingSet.prototype and stops there, so the line ends with the bricks. bricks.suitsAge(9) finds nothing on bricks or BuildingSet.prototype, and climbs one more link to Toy.prototype.
  • A parent’s method that calls this.describe() gets the child’s version. The new .label() method in Toy is found on Toy.prototype and called with bricks as this, so this.describe() inside it starts a new lookup at bricks and finds the BuildingSet override first.
  • super starts one level up. Inside the BuildingSet override, super.describe() starts at Toy.prototype, one link above BuildingSet.prototype, where the override is written. It finds the Toy version, not the override again, and this still points to bricks.
  • instanceof walks the same chain. bricks instanceof BuildingSet and bricks instanceof Toy are both true, because BuildingSet.prototype and Toy.prototype are both on the chain from bricks. bricks instanceof DressUp is false, since DressUp.prototype isn’t on that chain.
  • Classes have a chain too. A class’s .prototype property is where its instances link. The class’s own prototype is a separate link, and extends points it at the class Toy. So BuildingSet.fromRecord(record) finds the static method on Toy one link up.
  • new this(...) builds the class the call started from. In a static method, this is the class before the dot. With new Toy(...), BuildingSet.fromRecord() built a plain Toy. With new this(...), it builds a BuildingSet.
  • A subclass with its own properties overrides fromRecord(). The Toy version only passes the values every toy has, so until BuildingSet has its own fromRecord(), the set’s brick count is undefined. The static fromRecord() on BuildingSet calls super.fromRecord(record). As with super.describe(), super only moves the start of the lookup up to Toy. The keyword this stays BuildingSet, so new this(...) still builds a set. Then it adds the brick count.
  • Built-in classes have chains too. A class can extend Map, and its instances are still maps. Keep your own families to one or two levels, so you can follow every lookup by eye.

The Final Code

toy.js, with the new .label() method and fromRecord() building new this(...):

Language: JavaScript Filename: toy.js
export class Toy {
  #minAge;

  constructor(id, name, minAge) {
    this.id = id;
    this.name = name;
    this.#minAge = minAge;
  }

  static fromRecord(record) {
    return new this(record.id, record.name, record.minAge);
  }

  suitsAge(age) {
    return age >= this.#minAge;
  }

  describe() {
    return `${this.id}: ${this.name} (ages ${this.#minAge}+)`;
  }

  label() {
    return `Shelf label: ${this.describe()}`;
  }
}

building-set.js, with its own static fromRecord():

Language: JavaScript Filename: building-set.js
import { Toy } from "./toy.js";

export class BuildingSet extends Toy {
  constructor(id, name, minAge, brickCount) {
    super(id, name, minAge);
    this.brickCount = brickCount;
  }

  static fromRecord(record) {
    const set = super.fromRecord(record);
    set.brickCount = record.brickCount;
    return set;
  }

  bagsNeeded() {
    return Math.ceil(this.brickCount / 250);
  }

  describe() {
    return `${super.describe()}, ${this.brickCount} bricks`;
  }
}

dress-up.js is unchanged from the last lesson:

Language: JavaScript Filename: dress-up.js
import { Toy } from "./toy.js";

export class DressUp extends Toy {
  constructor(id, name, minAge, size) {
    super(id, name, minAge);
    this.size = size;
  }

  describe() {
    return `${super.describe()}, size ${this.size}`;
  }
}

chain.js follows the instance chain from bricks, one link at a time:

Language: JavaScript Filename: chain.js
import { Toy } from "./toy.js";
import { BuildingSet } from "./building-set.js";
import { DressUp } from "./dress-up.js";

const bricks = new BuildingSet("T02", "Building set", 8, 1000);
console.log("Own describe?", Object.hasOwn(bricks, "describe"));
console.log("Link 1:", Object.getPrototypeOf(bricks) === BuildingSet.prototype);
console.log("Link 2:", Object.getPrototypeOf(BuildingSet.prototype) === Toy.prototype);
console.log(bricks.describe());
console.log("Suits Priya (9):", bricks.suitsAge(9));
console.log(bricks.label());
console.log("A BuildingSet?", bricks instanceof BuildingSet);
console.log("A Toy?", bricks instanceof Toy);
console.log("A DressUp?", bricks instanceof DressUp);

Run it with Node, and each line answers one question about the chain:

Language: Shell
$ node chain.js
Own describe? false
Link 1: true
Link 2: true
T02: Building set (ages 8+), 1000 bricks
Suits Priya (9): true
Shelf label: T02: Building set (ages 8+), 1000 bricks
A BuildingSet? true
A Toy? true
A DressUp? false

records.js follows the classes’ chain:

Language: JavaScript Filename: records.js
import { Toy } from "./toy.js";
import { BuildingSet } from "./building-set.js";

const record = { id: "T02", name: "Building set", minAge: 8, brickCount: 1000 };
console.log("Own fromRecord?", Object.hasOwn(BuildingSet, "fromRecord"));
console.log("Link:", Object.getPrototypeOf(BuildingSet) === Toy);

const bricks = BuildingSet.fromRecord(record);
console.log("A BuildingSet?", bricks instanceof BuildingSet);
console.log(bricks.describe());

With the final toy.js and building-set.js, it prints:

Language: Shell
$ node records.js
Own fromRecord? true
Link: true
A BuildingSet? true
T02: Building set (ages 8+), 1000 bricks

Next, in Exercise: Add a New Kind of Toy, you’ll add the library’s first musical toy to the family, with the batteries it takes and a note for the volunteers to tape to its box. The code runs right here on the page, and automated tests check it each time you run it, so run your code early and often.

00:00 The toy library’s tracker now has a family: Toy, and two kinds of toy that extend it. One loop calls describe on every toy on the shelf, and each line comes out right for its kind.

00:13 So how does JavaScript pick which describe runs? And where does super start looking? You’ll follow each call up a chain, one link at a time.

00:24 Take the 1,000-brick set, made in a script as bricks. Its own properties are its data, and Object.hasOwn() says describe isn’t one of them: false.

00:37 Is its prototype BuildingSet.prototype, where the class keeps its methods? True. And extends added a second link. Is Toy.prototype the next link up?

00:49 True.

00:52 Now call describe on bricks. JavaScript looks at bricks first, and finds nothing. It follows the link up to BuildingSet.prototype, and finds the override there.

01:03 It stops at that first match, so the line ends with the bricks. Does the set suit Priya, who’s nine? Neither bricks nor BuildingSet.prototype has suitsAge.

01:16 So the lookup climbs one more link, to Toy.prototype, and finds it there: true.

01:22 For any method call, look on the object first, then take the first match up the chain.

01:30 The volunteers want shelf labels, so Toy gets one more method, label. It returns Shelf label, then whatever describe gives for this toy. BuildingSet has no label method of its own.

01:44 Your turn: pause the video and predict whether the building set’s label mentions its bricks.

01:55 It does, with all 1,000 bricks. JavaScript found label on Toy.prototype and called it with bricks as this. So inside label, the call to describe starts a new lookup at bricks, and finds the override first.

02:12 A parent’s method that calls describe gets the child’s version.

02:17 Now look inside BuildingSet’s describe. It calls super.describe(). That lookup doesn’t start at bricks. It starts one link above BuildingSet.prototype, where the override is written.

02:30 So at Toy.prototype, it finds Toy’s describe, not the override again. And the keyword this still points to bricks, so Toy’s part of the line describes the set.

02:42 The instanceof operator walks the same chain. Is bricks a BuildingSet? BuildingSet.prototype is on its chain: true. A Toy? Toy.prototype is one link further up: true.

02:57 A dress-up box? DressUp.prototype isn’t on this chain at all: false.

03:05 Classes have a chain too. Take the static method that builds a toy from a saved record. BuildingSet has no fromRecord of its own: false. The class’s prototype property is where its instances link.

03:19 The class’s own prototype is a separate link, which extends pointed at Toy: true. So a call on BuildingSet finds Toy’s static, one link up. But the set it builds isn’t a BuildingSet: false.

03:35 Toy’s version says new Toy, so it builds a plain toy, with no bricks. To fix it, swap new Toy for new this, in Toy’s version. Inside a static method, the keyword this holds the class the call started from, the one before the dot.

03:56 Called on BuildingSet, it builds a BuildingSet: true. However, the brick count is undefined. Toy’s version only passes the values every toy has. So BuildingSet overrides fromRecord too.

04:11 Its version calls super.fromRecord() first. As with describe, super only changes where the lookup starts: at Toy. The keyword this stays BuildingSet, so new this still builds a set.

04:26 Then it adds the brick count, and the set has all its bricks.

04:31 So a lookup starts at the object before the dot: the instance for a method, and the class for a static. JavaScript takes the first match up the chain. Super starts one level above where the method is written, and instanceof walks the same links.

04:48 Built-in classes have chains too. A class can extend Map, and its instances are still Maps. That’s all you need about extending built-ins for now. Keep your own families to one or two levels, so you can follow every lookup by eye.

05:05 Next, in Exercise: Add a New Kind of Toy, you’ll add a musical toy to the library’s family.

Become a Member to join the conversation.