One blueprint, many objects

INPUT · Slides

Calling the parent's work, then adding to it

01 / 05

You want an extra property on the child alone

You want a truck to hold "the weight it can carry". But a bicycle does not need that.

Which means you want to rewrite the constructor on the child alone. Just like a method, a constructor can be overridden.

02 / 05

Call the parent's work with super()

Write a constructor on the child and the parent's constructor stops running by itself. So you have to write super(...) to call it yourself.

super(name) means "hand name to the parent's constructor and run it". The rule is that it goes before you use this.

class Vehicle {  constructor(name) {    this.name = name;  }}class Truck extends Vehicle {  constructor(name, weight) {    super(name);    this.weight = weight;  }}const t = new Truck("big truck", 500);console.log(t.name);console.log(t.weight);

Result

big truck
500

03 / 05

Leave the parent's business to the parent

Writing this.name = name; again on the child would work, but then the same thing is written in two places.

Use super() and you get the shape the parent's part left to the parent, the child writing only the difference. That is the cleanest use of inheritance.

04 / 05

super works for methods too

When you have overridden a method, sometimes you want the parent's original work as well. For that you write super.methodName().

It gives you the shape "do the parent's, then add mine".

class Vehicle {  constructor(name) {    this.name = name;  }  info() {    console.log(`name: ${this.name}`);  }}class Truck extends Vehicle {  constructor(name, weight) {    super(name);    this.weight = weight;  }  info() {    super.info();    console.log(`load limit: ${this.weight}kg`);  }}const t = new Truck("big truck", 500);t.info();

Result

name: big truck
load limit: 500kg

05 / 05

A guide to which to write

When overriding, think about whether to use super like this.

  • you do not want the parent's work at all → do not write super
  • you want to add to the parent's work → call super, then write the difference

That covers the basics of classes. Have a go at the finishing exercises.