What is the difference between class-based and prototype-based inheritance in JavaScript?
Asked on Aug 05, 2024
Answer
JavaScript supports both class-based and prototype-based inheritance, but they are implemented differently. Class-based inheritance uses the "class" keyword, while prototype-based inheritance relies on objects and prototypes directly.
// Class-based inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog('Rex');
dog.speak(); // Rex barks.
// Prototype-based inheritance
function AnimalProto(name) {
this.name = name;
}
AnimalProto.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function DogProto(name) {
AnimalProto.call(this, name);
}
DogProto.prototype = Object.create(AnimalProto.prototype);
DogProto.prototype.constructor = DogProto;
DogProto.prototype.speak = function() {
console.log(`${this.name} barks.`);
};
const dogProto = new DogProto('Buddy');
dogProto.speak(); // Buddy barks.
Additional Comment:
✅ Answered with JavaScript best practices.- Class-based inheritance uses the "class" and "extends" keywords, making it more syntactically similar to other object-oriented languages.
- Prototype-based inheritance uses constructor functions and the "prototype" property to achieve inheritance.
- Both approaches ultimately rely on JavaScript's prototype chain, but classes provide a more intuitive syntax.
- In ES6+, class-based syntax is preferred for its readability and ease of use.
Recommended Links:
← Back to All Questions