Hone

Lessons · TypeScript · extends and super

extends shares a parent; super reaches it

class Puppy extends Dog makes every Dog method work on a Puppy. super(...) runs the parent's constructor, and a method of the same name in the child overrides the parent's.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A savings account is an account with interest; an admin is a user with extra powers; a button is a widget that clicks. The shared part is written once on the parent and every child gets it.

How to think about it

Ask: is this a KIND OF that? If yes, extend. In the child's constructor call super(...) before touching this, because the parent is what creates this.

Worked example

class Dog {
  constructor(name) { this.name = name; }
  speak() { return this.name + ' says Woof'; }
}
class Puppy extends Dog {
A Puppy is a Dog.
  constructor(name) {
    super(name);
The parent sets up name first.
    this.age = 0;
Then what only a Puppy has.
  }
  speak() { return this.name + ' says Yip'; }
Override: the child's version wins.
}
const bo = new Puppy('Bo');
console.log(bo.speak(), bo instanceof Dog);
Bo says Yip true

Your turn

Let the parent set up the shared fields first.

class Admin extends User {
  constructor(name) {
    (name);
    this.powers = ['ban'];
  }
}

The trap

Using this before super() in a derived constructor. It throws a ReferenceError, because until the parent constructor runs there is no object yet.

Practise extends and super on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.