Learn JavaScript · lesson 55 of 60 · about 9 minutes
extends and super
Build a class on top of another, reuse what it has and change what you need.
What you'll learn
- Make a child class with extends
- Call the parent's constructor with super()
- Override a method and call the parent's version
A big bug
Some bugs are harder: a memory leak has a shield, and every hit on it loses that much before it does any work. A big bug is still a bug, with a name, hp, fixed and status, so BigBug extends Bug gets all of that for free. It only changes two things: takeHit(damage) passes damage - shield on to the parent's takeHit, and status adds the shield to the parent's status, like Memory leak: 6 of 10 hp left (shield 2). bigBugData gives the big bug as [name, hp, shield], and bigHits are Sam's first hits on it.
Classes that share
class Dog extends Animal makes Dog a child of Animal. Every Dog gets Animal's methods for free and can add its own.
If the child has a constructor, it must call super(...) first. That runs the parent's constructor so the shared properties get set up.
Dog extends Animal
class Animal {
constructor(name) {
this.name = name;
}
eat() {
return `${this.name} eats`;
}
}
class Dog extends Animal {
constructor(name, trick) {
super(name);
this.trick = trick;
}
perform() {
return `${this.name} does ${this.trick}`;
}
}
const rex = new Dog("Rex", "a roll");
console.log(rex.eat());
console.log(rex.perform());
console.log(rex instanceof Animal);Output
Rex eats
Rex does a roll
trueOverriding
If the child has a method with the same name as the parent's, the child's wins: it overrides it. super.method() still runs the parent's version, so you can build on it instead of starting again.
Building on the parent
class Message {
format(text) {
return text;
}
}
class Shout extends Message {
format(text) {
return super.format(text).toUpperCase() + "!";
}
}
console.log(new Message().format("hi"));
console.log(new Shout().format("hi"));Output
hi
HI!super works for getters too
super.status reads the parent's getter, so BigBug doesn't repeat how a status is worked out: it takes Memory leak: 6 of 10 hp left from Bug and adds (shield 2). The same goes for super.takeHit(...): the rule that hp never goes below 0 stays in one place, in Bug.
Tip
Using this in a child's constructor before calling super() throws a ReferenceError, because the object isn't set up yet.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.