JavaScript Class Inheritance
Inheritance lets one class build on another, reusing its properties and methods while adding or customizing behavior.
Why inheritance?
Often several classes share common behavior. Rather than duplicating that code, you can put the shared parts in a base class (also called a parent or superclass) and have more specialized classes extend it. The child class automatically gains everything from the parent and can then add its own features or replace inherited ones.
The extends and super keywords
- extends creates a child class that inherits from a parent class.
- super(...) inside a child constructor calls the parent constructor to set up inherited properties.
- super.method() calls the parent's version of a method from inside an overridden method.
- You must call super() before using this in a child constructor.
Extending a base class
<!DOCTYPE html>
<html>
<body>
<h2>Class Inheritance</h2>
<script>
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return this.name + " makes a sound.";
}
}
class Dog extends Animal {
speak() {
return this.name + " barks.";
}
}
const rex = new Dog("Rex");
console.log(rex.speak()); // "Rex barks."
console.log(rex.name); // "Rex" (inherited)
</script>
</body>
</html>Note: When a child class defines a method with the same name as the parent, the child's version wins. This is called overriding. The parent method is still reachable through super.
Using super in the constructor and methods
<!DOCTYPE html>
<html>
<body>
<h2>Using super</h2>
<script>
class Vehicle {
constructor(brand) {
this.brand = brand;
}
describe() {
return "A " + this.brand;
}
}
class Car extends Vehicle {
constructor(brand, doors) {
super(brand); // set up parent part first
this.doors = doors;
}
describe() {
return super.describe() + " with " + this.doors + " doors";
}
}
const c = new Car("Toyota", 4);
console.log(c.describe()); // "A Toyota with 4 doors"
</script>
</body>
</html>A chain of inheritance
<!DOCTYPE html>
<html>
<body>
<h2>Chain of Inheritance</h2>
<script>
class Shape {
area() { return 0; }
}
class Rectangle extends Shape {
constructor(w, h) {
super();
this.w = w;
this.h = h;
}
area() { return this.w * this.h; }
}
class Square extends Rectangle {
constructor(size) {
super(size, size);
}
}
console.log(new Square(5).area()); // 25
</script>
</body>
</html>Note: Forgetting to call super() in a child constructor, or referencing this before calling it, throws a reference error. Always call super() first when the child defines its own constructor.