Classical vs Prototypal Inheritance in JavaScript
What is the difference between classical inheritance and prototypal inheritance?
Inheritance is a fundamental concept in object-oriented programming that allows one object to inherit properties and methods from another. In JavaScript, two primary types of inheritance are commonly discussed: classical inheritance and prototypal inheritance. Although JavaScript is inherently a prototype-based language, it can simulate classical inheritance patterns. Understanding the distinction is essential for building efficient and maintainable applications. MDN’s guide to inheritance and the prototype chain goes deeper.
1. Classical Inheritance
Classical inheritance is the model used in many object-oriented languages like Java, C++, and C#. In this model, classes are blueprints for creating objects. Subclasses inherit from parent classes using keywords like extends or super.
Example (Classical Style in ES6):
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a noise.`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks.`;
}
}
const dog = new Dog("Rex");
console.log(dog.speak()); // Rex barks.
Key Characteristics:
- Class-based syntax
- Constructor functions define object structure
- Methods are defined on the class prototype
- Inheritance achieved through subclassing
2. Prototypal Inheritance
Prototypal inheritance uses objects directly. An... premium content.
