Extending Functionality
Classes can inherit from each other using the extends keyword.
class Animal {
constructor(name) { this.name = name; }
eat() { console.log(this.name + ' is eating.'); }
toString() { return `Animal: ${this.name}`; }
}
class Rabbit extends Animal {
hide() { console.log(this.name + ' hides!'); }
}
let rabbit = new Rabbit('White Rabbit');
rabbit.eat(); // Inherited from Animal
rabbit.hide(); // Rabbit's own method
Overriding Methods with super
class Dog extends Animal {
constructor(name, breed) {
super(name); // MUST call super() before using this
this.breed = breed;
}
eat() {
super.eat(); // Call the parent's eat() first
console.log('...and wags tail!');
}
}
let dog = new Dog('Rex', 'Labrador');
dog.eat();
// "Rex is eating."
// "...and wags tail!"
Important
If a child class has its own constructor, it must call super() before it can use this. Forgetting this causes a ReferenceError.
Tip
super.method() calls the parent's original method, even if you've overridden it in the child class.