Class Inheritance in JavaScript
? Class Inheritance in JavaScript
Inheritance allows one class (child) to inherit properties and methods from another class (parent), promoting code reuse and organization.
? Basic Syntax: ES6 Classes and Inheritance
// Parent classclass Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound.`); }}// Child class extends Animalclass Dog extends Animal { constructor(name, breed) { super(name); // Call parent constructor this.breed = breed; } speak() { console.log(`${this.name} barks.`); }}const dog = new Dog("Buddy", "Golden Retriever");dog.speak(); // Output: Buddy barks.? Explanation
class Dog extends Animal— Dog inherits from Animalsuper(name)— calls the constructor of the parent classChild class can override parent methods (
speakin example)Child class can add new properties or methods
? More Features
1. Calling Parent Methods From Child
class Cat extends Animal { speak() { super.speak(); // Calls Animal's speak() console.log(`${this.name} meows.`); }}const cat = new Cat("Whiskers");cat.speak();// Output:// Whiskers makes a sound.// Whiskers meows.2. Inheriting Without Adding Anything
class Bird extends Animal {}const bird = new Bird("Tweety");bird.speak(); // Tweety makes a sound.? Why Use Class Inheritance?
Code reuse
Logical grouping of similar objects
Easier maintenance
Polymorphism (overriding methods)
?? Notes
JavaScript uses prototype-based inheritance under the hood.
ES6
classsyntax is mostly syntactic sugar over prototypes.You can also create inheritance using constructor functions and prototypes (older style).
If you want, I can also show you prototype-based inheritance or examples with multiple levels of inheritance. Just ask!