JavaScript Class Inheritance

Class inheritance in JavaScript allows one class to inherit properties and methods from another class. The extends keyword is used to create a subclass, and the super keyword is used to call the parent class's constructor or methods.

Key Topics

Basic Inheritance

A subclass can inherit all properties and methods from its parent class using the extends keyword.

class Animal {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(`${this.name} makes a sound.`);
    }
}
class Dog extends Animal {
    bark() {
        console.log(`${this.name} barks.`);
    }
}
const dog = new Dog("Buddy");
dog.speak();
dog.bark();

Output

> Buddy makes a sound.

> Buddy barks.

Explanation: The Dog class inherits the speak method from the Animal class and defines its own bark method.

Overriding Methods

A subclass can override a method from its parent class by redefining it in the subclass.

class Bird extends Animal {
    speak() {
        console.log(`${this.name} chirps.`);
    }
}
const bird = new Bird("Tweety");
bird.speak();

Output

> Tweety chirps.

Explanation: The speak method in the Bird class overrides the speak method in the Animal class to provide customized behavior.

Calling Parent Methods

The super keyword can be used to call methods from the parent class.

class Cat extends Animal {
    speak() {
        super.speak();
        console.log(`${this.name} meows.`);
    }
}
const cat = new Cat("Kitty");
cat.speak();

Output

> Kitty makes a sound.

> Kitty meows.

Explanation: The Cat class uses super.speak() to invoke the parent class's speak method before adding its own behavior.

JavaScript Usage in DOM

Below is a complete DOM example demonstrating class inheritance for dynamically updating content.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Class Inheritance in DOM</title>
</head>
<body>
    <button onclick="showMessage()">Show Message</button>
    <p id="output"></p>

    <script>
        class Animal {
            constructor(name) {
                this.name = name;
            }
            speak() {
                return `${this.name} makes a sound.`;
            }
        }
        class Dog extends Animal {
            speak() {
                return `${this.name} barks.`;
            }
        }
        function showMessage() {
            const dog = new Dog("Buddy");
            document.getElementById("output").textContent = dog.speak();
        }
    </script>
</body>
</html>

Key Takeaways

  • Inheritance: Use extends to create subclasses.
  • Method Overriding: Customize parent class methods in subclasses.
  • super Keyword: Call parent class methods for extended functionality.
  • DOM Integration: Leverage inheritance to simplify dynamic content generation.