Member-only story
JavaScript offers multiple approaches to inheritance, with classical and prototypal being the two primary methods. Each has its own merits and use cases. In this article, we’ll compare classical and prototypal inheritance in JavaScript, providing clear explanations and contemporary code examples to help you grasp these concepts effectively.
Classical Inheritance
Classical inheritance is the inheritance model typically found in class-based languages like Java or C++. In JavaScript, classical inheritance can be emulated using constructor functions and the new
keyword.
Let’s see an example:
// Parent Class
function Animal(name) {
this.name = name;
}
// Method for Parent Class
Animal.prototype.introduce = function() {
console.log("Hi, I'm " + this.name);
};
// Child Class
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
// Inheriting Methods from Parent Class
Dog.prototype = Object.create(Animal.prototype);
// Method for Child Class
Dog.prototype.bark = function() {
console.log("Woof!");
};
// Creating Instances
const myDog = new…