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 readingthis. super.method()calls the parent's version — useful for "do parent's thing plus mine".super.method()works in instance methods.superinsidestaticmethods reaches the parent class.extendscan 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 functions | The "is-a" relationship is forced. |
| Mixins | You 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 = []; } }
Five letters.
Discussion
Loading…