Build One Class on Another
JavaScript Class Inheritance
Use `extends` and `super` to build a child class that reuses and extends a parent class.
What you'll learn
- Inherit with `extends`
- Call the parent constructor with `super(...)`
- Override methods and call the parent version
extends makes one class build on another. The child class inherits
everything from the parent — properties, methods, and the chain of
prototypes.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
bark() {
return `${this.name} says woof!`;
}
}
const rex = new Dog("Rex");
console.log(rex.speak()); // "Rex makes a sound" ← inherited from Animal
console.log(rex.bark()); // "Rex says woof!" ← Dog's own method super(...) — Call the Parent Constructor
When the child has its own constructor, it MUST call super(...)
before using this.
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // call Animal's constructor — required before `this`
this.breed = breed;
}
}
const rex = new Dog("Rex", "Labrador");
console.log(rex); // Dog { name: 'Rex', breed: 'Labrador' } Overriding Methods
A child class can replace a parent method by re-declaring it.
class Animal {
speak() {
return "generic animal sound";
}
}
class Cat extends Animal {
speak() {
return "meow";
}
}
const a = new Animal();
const c = new Cat();
console.log(a.speak()); // "generic animal sound"
console.log(c.speak()); // "meow" Calling the Parent Method from an Override
Use super.method(...) to call the parent’s version inside an override.
class Animal {
describe() {
return "I am an animal.";
}
}
class Dog extends Animal {
describe() {
return super.describe() + " Specifically, I am a dog.";
}
}
const rex = new Dog();
console.log(rex.describe());
// "I am an animal. Specifically, I am a dog." instanceof
Use instanceof to test whether an object is an instance of a class
(or its parents).
class Animal {}
class Dog extends Animal {}
const rex = new Dog();
console.log(rex instanceof Dog); // true
console.log(rex instanceof Animal); // true ← also true through inheritance
console.log(rex instanceof Object); // true When to Use Inheritance
Inheritance is a strong commitment — the child is locked into the parent’s shape. Use it sparingly. Common signals:
- The child is genuinely a more specific kind of the parent
(
Dog extends Animal,AdminUser extends User). - You’ll genuinely override or extend a method.
- The relationship is stable.
Often, composition (passing functionality in as a value) is more flexible than inheritance. Modern JavaScript leans toward composition.
Up Next
A real privacy primitive: # private fields.