Lesson 26 of 34 · Classes & Errors
JavaScript Inheritance: extends, super and static
Your game has archers, knights and mages. They're all units: each has a name and a power, and each can attack and describe itself. But each kind also has its own twist. Copy-pasting the shared code into three classes would be a maintenance nightmare.
Inheritance solves this: a class can extend another class, reuse everything it has, and add or change only what's different.
extends: building on a parent class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
fetch() {
return `${this.name} fetches the stick!`;
}
}
const rex = new Dog("Rex");
console.log(rex.speak()); // Rex makes a sound. (inherited from Animal)
console.log(rex.fetch()); // Rex fetches the stick!
console.log(rex instanceof Dog, rex instanceof Animal); // true true
Dog is the child (subclass) and Animal is the parent (superclass). A Dog instance has everything an Animal has, plus its own methods.
super() in the constructor
If the child class needs its own constructor, it must call super(...) before touching this. super(...) runs the parent's constructor, which sets up the inherited properties:
class Wolf extends Animal {
constructor(name, packSize) {
super(name); // let Animal set this.name
this.packSize = packSize; // then add Wolf's own property
}
}
Forgetting super() throws a ReferenceError as soon as you create an instance.
Overriding methods and calling the parent
A child can override a method by defining one with the same name. Inside it, super.method() calls the parent's version, so you can extend behaviour instead of rewriting it:
class Cat extends Animal {
speak() {
return `${super.speak()} Meow!`;
}
}
console.log(new Cat("Tom").speak()); // Tom makes a sound. Meow!
This is polymorphism: you can call speak() on any animal without knowing its exact class, and each one responds in its own way.
Static methods and fields
Some functionality belongs to the class itself rather than to any one instance. Mark it static, and call it on the class:
class Dice {
static sides = 6;
static roll() {
return Math.floor(Math.random() * Dice.sides) + 1;
}
}
console.log(Dice.roll()); // a number from 1 to 6
// new Dice().roll(); // throws a TypeError: instances don't have static methods
Static methods are commonly used as factories (User.fromJSON(text)), as utilities that work on several instances (Unit.strongest(units)), or for shared configuration. Static members are inherited too: if Unit has a static method, Archer.strongest(...) works as well.
When to use inheritance
Keep hierarchies shallow: one or two levels is usually plenty. If you find yourself building deep chains like Entity → Creature → Animal → Mammal → Dog, consider giving objects small helper objects instead (composition). The real world rarely fits a perfect tree.
Common mistakes
- Using
thisbeforesuper()in a child constructor:ReferenceError. - Forgetting
returnwhen overriding:speak() { super.speak(); }returnsundefined. - Calling a static method on an instance.
archer.strongest()doesn't exist; useUnit.strongest().
Assignment
The starter contains a working Unit class. Build on it:
- Add a static method
Unit.strongest(units)that returns the unit with the highestpowerfrom an array, ornullif the array is empty. - Write
class Archer extends Unit:constructor(name, power, arrows)callssuperand storesarrows(default3).attack(): while the archer has arrows, it uses one arrow and deals double power. With no arrows left, it falls back to the regularUnitattack.
- Write
class Knight extends Unitthat overridesdescribe()to return the normal description followed by" [armored]".
const robin = new Archer("Robin", 4, 1);
robin.attack(); // 8 (uses the only arrow)
robin.attack(); // 4 (no arrows: regular attack)
new Knight("Lancelot", 6).describe(); // "Lancelot (power 6) [armored]"
Unit.strongest([robin, new Knight("Lancelot", 6)]); // the knightPremium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Inheritance in other languages
- Python Inheritance and super() · Python
- Go Struct Embedding and Composition · Go
- Java Inheritance: extends and super · Java
- C# Inheritance: virtual, override and base · C#
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .