Inheritance
Inheritance is a core principle of OOP. It allows you to create a "Child" class that automatically inherits all the logic and traits from a "Parent" class, while still allowing the Child to have its own unique logic.
In JavaScript, this is achieved via the extends keyword in combination with super.
Extends and Super
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
// Dog INHERITS from Animal
class Dog extends Animal {
constructor(name, breed) {
// 'super' actively fires the parent Animal constructor!
super(name);
this.breed = breed;
}
// Overriding the parent's method (Polymorphism)
speak() {
console.log(`${this.name} barks loudly!`);
}
fetch() {
console.log(`${this.name} fetches the stick.`);
}
}
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.speak(); // "Buddy barks loudly!" (Uses the child method)
myDog.fetch(); // "Buddy fetches the stick."
The Prototype Chain Concept
When you invoke myDog.speak(), the JS Engine handles inheritance under the hood via the Prototype Chain:
- It checks the
myDoginstance itself. - It checks the
Dogprototype. (Found it! Executes.) - If it wasn't there, it would travel up to the
Animalprototype. - If not there, it travels up to the master
Objectprototype.