Class Inheritance
Class Inheritance
Section titled “Class Inheritance”Introduction
Section titled “Introduction”ES6 classes provide a cleaner syntax for inheritance. The extends keyword sets up the prototype chain automatically, and super calls the parent class.
Basic Class Inheritance
Section titled “Basic Class Inheritance”class Animal { constructor(name) { this.name = name; }
eat() { return `${this.name} is eating`; }}
class Dog extends Animal { constructor(name, breed) { super(name); // calls Animal constructor this.breed = breed; }
bark() { return `${this.name} says woof!`; }}
const rex = new Dog('Rex', 'Labrador');console.log(rex.eat()); // 'Rex is eating' — inheritedconsole.log(rex.bark()); // 'Rex says woof!' — ownMethod Overriding
Section titled “Method Overriding”class Animal { speak() { return 'Some sound'; }}
class Dog extends Animal { speak() { return 'Woof!'; // overrides parent }}
const dog = new Dog();console.log(dog.speak()); // 'Woof!'Calling Parent Methods with super
Section titled “Calling Parent Methods with super”class Animal { speak() { return 'Some sound'; }}
class Dog extends Animal { speak() { const parentMessage = super.speak(); // call parent return `${parentMessage} → Woof!`; // extend it }}
const dog = new Dog();console.log(dog.speak()); // 'Some sound → Woof!'Multi-level Inheritance
Section titled “Multi-level Inheritance”class Animal { constructor(name) { this.name = name; } eat() { return `${this.name} is eating`; }}
class Mammal extends Animal { constructor(name, hasFur) { super(name); this.hasFur = hasFur; } walk() { return `${this.name} is walking`; }}
class Dog extends Mammal { constructor(name, breed) { super(name, true); // Mammals have fur this.breed = breed; } bark() { return `${this.name} says woof!`; }}
const rex = new Dog('Rex', 'Lab');console.log(rex.eat()); // Animal methodconsole.log(rex.walk()); // Mammal methodconsole.log(rex.bark()); // Dog methodsuper() Rules
Section titled “super() Rules”- Must call
super()before accessingthisin a subclass constructor - If a subclass has a constructor,
super()is required - Without a constructor,
super()is automatically called
Summary
Section titled “Summary”extendssets up prototype chain automaticallysuper()calls parent constructorsuper.method()calls parent method- Method overriding is straightforward
- Multi-level inheritance works through the chain