Skip to content
Codewilds

Lesson 26 of 34 · Classes & Errors

JavaScript Inheritance: extends, super and static

medium20 XP3 min read

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 this before super() in a child constructor: ReferenceError.
  • Forgetting return when overriding: speak() { super.speak(); } returns undefined.
  • Calling a static method on an instance. archer.strongest() doesn't exist; use Unit.strongest().

Assignment

The starter contains a working Unit class. Build on it:

  1. Add a static method Unit.strongest(units) that returns the unit with the highest power from an array, or null if the array is empty.
  2. Write class Archer extends Unit:
    • constructor(name, power, arrows) calls super and stores arrows (default 3).
    • attack(): while the archer has arrows, it uses one arrow and deals double power. With no arrows left, it falls back to the regular Unit attack.
  3. Write class Knight extends Unit that overrides describe() 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 knight

Premium 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
Play the 8 free lessons

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

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 26 is part of the full course. The first 8 lessons are free.

Premium 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
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.