iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Class Inheritance

extends creates a subclass. super reaches the parent — both inside constructor and inside methods.

Basic inheritance

JS
class Animal {
  constructor(name) { this.name = name; }
  speak()           { return `${this.name} makes a sound.`; }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);                 // must be called BEFORE using `this`
    this.breed = breed;
  }

  // Override
  speak() {
    return `${super.speak()} Woof!`;   // call the parent's version
  }
}

const rex = new Dog("Rex", "labrador");
rex.speak();                     // "Rex makes a sound. Woof!"
rex instanceof Dog;              // true
rex instanceof Animal;           // true

Rules to remember

  • Subclass constructor must call super(args) before reading this.
  • super.method() calls the parent's version — useful for "do parent's thing plus mine".
  • super.method() works in instance methods. super inside static methods reaches the parent class.
  • extends can take any expression that returns a constructor — useful for mixins.

Mixin pattern

JS allows only single inheritance, but you can mix behaviour via factory functions:

JS
const Serializable = (Base) => class extends Base {
  toJSON() { return { ...this }; }
};

class User extends Serializable(Object) {
  constructor(name) { super(); this.name = name; }
}

JSON.stringify(new User("Ada"));   // '{"name":"Ada"}'

When NOT to inherit

Better than inheritance…Use when
Composition (an object holds another)"Has-a" relationship — a Car has an Engine.
Plain functionsThe "is-a" relationship is forced.
MixinsYou need multiple unrelated behaviours.
Tip: Deep inheritance hierarchies are a maintenance nightmare. Keep chains short (one or two levels) — reach for composition when you're tempted to extend a third time.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Class Inheritance!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Call the parent constructor before using `this`.

class Dog extends Animal { constructor(name) { (name); this.tricks = []; } }

Test yourself

Q1. In a subclass constructor you must call…
Q2. `super.method()` inside a subclass calls…
Q3. A common alternative to deep inheritance is…

Discussion

Loading…