Member-only story
JavaScript’s object-oriented inheritance system has seen significant improvements over the years, making it more streamlined and developer-friendly. In this article, we’ll explore the evolution of inheritance from ES5 to ES6+ and beyond, with clear code examples to illustrate the changes.
ES5: Prototypal Inheritance
Prior to ES6, JavaScript relied solely on prototypal inheritance. This approach involved creating objects and inheriting properties and methods from a prototype object. Here’s an example:
// Parent constructor function
function Animal(name) {
this.name = name;
}
// Adding a method to the prototype
Animal.prototype.sayHello = function() {
console.log(`Hello, I'm ${this.name}`);
}
// Child constructor function
function Dog(name, breed) {
Animal.call(this, name); // Inheriting from Animal
this.breed = breed;
}
// Linking prototypes
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// Adding a method to Dog's prototype
Dog.prototype.bark = function() {
console.log('Woof!');
}
const buddy = new Dog('Buddy', 'Golden Retriever');
buddy.sayHello(); // Output: "Hello, I'm Buddy"
buddy.bark(); // Output: "Woof!"