typestar

Extending a class in JavaScript

extends, super, and how instanceof sees the chain.

class Step {
  constructor(title) {
    this.title = title;
  }

  describe() {
    return `step: ${this.title}`;
  }
}

class Encore extends Step {
  constructor(title, lines) {
    super(title);
    this.lines = lines;
  }

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

const encore = new Encore("crawler.go", 67);
console.log(encore.describe());
console.log(encore instanceof Encore, encore instanceof Step);
console.log(Object.getPrototypeOf(Encore) === Step);

How it works

  1. super(...) must run before this is touched.
  2. A method can call super.method() to reach the parent's version.
  3. #private members are not visible to a subclass.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
460
Tokens
128
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 3 of 3 in Classes, step 37 of 43 in Language basics.

← Previous Next →