Inheritance
Inheritance lets one class build on another, reusing properties and methods while adding or overriding what it needs.
I. Extending a class
Use extends to create a subclass. The subclass gets everything the parent class has.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const d = new Dog("Rex");
console.log(d.speak()); // Rex barks.
console.log(d.name); // Rex (inherited from Animal)
Dog overrides speak() with its own version. Properties set in Animal’s constructor (this.name) are still accessible because Dog extends it.
II. Calling the parent constructor with super()
When a subclass has its own constructor, it must call super() before using this. super() runs the parent class’s constructor.
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() {
return `${this.name} says ${this.sound}.`;
}
}
class Dog extends Animal {
constructor(name) {
super(name, "woof"); // calls Animal's constructor
this.tricks = [];
}
learn(trick) {
this.tricks.push(trick);
}
showTricks() {
return `${this.name} knows: ${this.tricks.join(", ")}`;
}
}
const dog = new Dog("Rex");
dog.learn("sit");
dog.learn("shake");
console.log(dog.speak()); // Rex says woof.
console.log(dog.showTricks()); // Rex knows: sit, shake
III. Calling a parent method with super.method()
Use super.methodName() inside a subclass to call the parent’s version of a method.
class Vehicle {
describe() {
return "This is a vehicle.";
}
}
class Car extends Vehicle {
describe() {
return super.describe() + " Specifically, a car.";
}
}
const car = new Car();
console.log(car.describe()); // This is a vehicle. Specifically, a car.
IV. Checking inheritance
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
instanceof checks the entire prototype chain, so a Dog instance is also an Animal.
V. When to use inheritance
Inheritance is useful when subclasses share meaningful “is-a” relationships with the parent. A Dog is an Animal, so inheritance fits.
When classes share behaviour but not identity, composition is usually a better choice: give each class the methods it needs directly, rather than inheriting from a common base. This avoids deep inheritance chains that become hard to change.
For more on classes, see Classes .