01 / 05
One blueprint, many objects
INPUT · Slides
Calling the parent's work, then adding to it
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.