Inheritance (extends & super)
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — A Class Built on Another
Imagine adding a special kind of Codémon: a legendary one, with everything a normal Codémon has plus a signature move. The naive approach is to copy the whole `Codemon` class and add one method — but now you have two copies of the same code to keep in sync forever:
class Codemon {
constructor(name, level) {
this.name = name;
this.level = level;
}
describe() {
return this.name + " Lv." + this.level;
}
}
class Legendary {
constructor(name, level) {
this.name = name;
this.level = level;
}
describe() {
return this.name + " Lv." + this.level;
}
signature() {
return this.name + " unleashes its signature move!";
}
}
const zap = new Codemon("Zap", 4);
const titan = new Legendary("Titanchu", 50);
console.log(zap.describe());
console.log(titan.signature());The `extends` keyword lets a class inherit everything from another one. `class Legendary extends Codemon` means: start from `Codemon`, keep its constructor and all its methods, and only add what's new:
class Codemon {
constructor(name, level) {
this.name = name;
this.level = level;
}
describe() {
return this.name + " Lv." + this.level;
}
}
class Legendary extends Codemon {
signature() {
return this.name + " unleashes its signature move!";
}
}
const titan = new Legendary("Titanchu", 50);
console.log(titan.describe());
console.log(titan.signature());`Legendary` never wrote a constructor or a `describe()` method, yet both work on `titan`: they were inherited from `Codemon`. In this relationship, `Codemon` is called the parent class and `Legendary` the child class.
Exercise 2 — Adding Properties With super
Often the child class needs extra properties of its own. It then writes its own `constructor` — but it must first let the parent set up the shared part. The keyword `super(...)` calls the parent's constructor:
class Codemon {
constructor(name, level) {
this.name = name;
this.level = level;
}
}
class Legendary extends Codemon {
constructor(name, level, title) {
super(name, level);
this.title = title;
}
}
const titan = new Legendary("Titanchu", 50, "Guardian of the Peak");
console.log(titan.name + " Lv." + titan.level);
console.log(titan.title);Here is what happens when you write `new Legendary("Titanchu", 50, "Guardian of the Peak")`: 1. The child constructor starts with the three values. 2. `super(name, level)` runs the `Codemon` constructor, which sets `this.name` and `this.level`. 3. Back in the child constructor, `this.title = title` adds the extra property. One strict rule: in a child constructor, `super(...)` must be called before any use of `this`. Until the parent constructor has run, the object isn't ready, and touching `this` too early throws a `ReferenceError`.
Exercise 3 — Quiz: Inherited or Not?
What does this code print?
class Animal {
speak() {
return "...";
}
}
class Codemon extends Animal {
attack() {
return "Hit!";
}
}
const zap = new Codemon();
console.log(zap.speak() + zap.attack());...Hit!Hit!undefinedHint : The child keeps every method of the parent and adds its own.
Exercise 4 — Extend and Call the Parent
Make `Legendary` inherit from `Codemon` and set up the shared part before adding its title.
Hint : One keyword links the two classes, another runs the parent's constructor from inside the child's.
Exercise 5 — Overriding a Method
A child class can replace an inherited method by writing a new one with the same name. This is called overriding. The child's version wins for its own instances, while the parent's instances keep the original:
class Codemon {
constructor(name) {
this.name = name;
}
attack() {
return this.name + " attacks";
}
}
class Legendary extends Codemon {
attack() {
return this.name + " attacks with legendary power";
}
}
const zap = new Codemon("Zap");
const titan = new Legendary("Titanchu");
console.log(zap.attack());
console.log(titan.attack());Both objects call `attack()`, but `zap` runs the `Codemon` version while `titan` runs the `Legendary` version. Sometimes the child doesn't want to throw the parent's behaviour away, but to build on it. Inside the overriding method, `super.methodName()` calls the parent's version, so you can reuse its result and add to it:
class Codemon {
constructor(name) {
this.name = name;
}
describe() {
return this.name;
}
}
class Legendary extends Codemon {
describe() {
return super.describe() + " (legendary)";
}
}
const titan = new Legendary("Titanchu");
console.log(titan.describe());`super.describe()` returns `"Titanchu"` from the parent's version, and the child's version appends `" (legendary)"` to it.
Exercise 6 — Quiz: Which Version Runs?
What does this code print?
class A {
hello() {
return "A";
}
}
class B extends A {
hello() {
return "B";
}
}
const x = new B();
console.log(x.hello());BAABHint : The closest definition wins for the child's instances.
Exercise 7 — Quiz: Extending the Parent
What does this code print?
class A {
hello() {
return "A";
}
}
class B extends A {
hello() {
return super.hello() + "B";
}
}
console.log(new B().hello());ABBABAHint : The child runs the parent's version first, then adds its own piece.
Exercise 8 — Extend the Description
Make the child's method reuse the parent's, then add a suffix.
Hint : One keyword reaches the parent's version, and the method being extended keeps its name.
Exercise 9 — Instances Belong to Both Classes
An instance of a child class is also an instance of its parent. `instanceof` answers `true` for both — which is exactly what you want: a legendary Codémon is a Codémon, so every function written for `Codemon` accepts it too:
class Codemon {
constructor(name) {
this.name = name;
}
}
class Legendary extends Codemon {}
const titan = new Legendary("Titanchu");
const zap = new Codemon("Zap");
console.log(titan instanceof Legendary);
console.log(titan instanceof Codemon);
console.log(zap instanceof Legendary);Read the three results: 1. `titan instanceof Legendary` is `true`: `titan` was built with `new Legendary(...)`. 2. `titan instanceof Codemon` is also `true`: `Legendary` extends `Codemon`, so `titan` counts as a Codémon as well. 3. `zap instanceof Legendary` is `false`: a plain Codémon is not a Legendary. Inheritance is a one-way street: it goes from the specific child up to the general parent, never the other way around.
Exercise 10 — Inheritance Cheat Sheet
Match each element with its role.
class B extends Asuper(...)super.method()Exercise 11 — Codémon Family Tree
Build a small family of classes: a general Codémon, and two specialised kinds that share its code but behave differently.
Step 1: `Codemon` takes a name and a level. `attack()` returns `"name deals X"` where X is the level times 2. Step 2: `Legendary extends Codemon`. Its constructor also takes a `title`. Its `attack()` reuses the parent's text and adds `" (legendary)"`. Step 3: `Baby extends Codemon`. It overrides `attack()` completely to return `"name is too young to fight"`. Step 4: create Zap (level 4), Titanchu (level 50, title `"Guardian"`) and a baby Aquachu (level 1). Print each attack, then `"Titanchu is a Codemon: X"` using `instanceof`.
Expected output:
Zap deals 8
Titanchu deals 100 (legendary)
Aquachu is too young to fight
Titanchu is a Codemon: true// Write your classes here
// Use them here