This article discusses inheritance approaches in ES5, focusing on three main methods: prototype-based inheritance, constructor inheritance, and parasitic inheritance. The article explains the benefits and drawbacks of each approach, providing code ex
In ES5, inheritance can be achieved through several approaches:
This is the most common approach in ES5. It involves creating a base class (parent) and then "subclassing" it by creating new objects that inherit the properties and methods of the base class. This is done by manipulating the__proto__
property of the subclass objects.__proto__
property of the subclass objects.
const Animal = { eat() { console.log("Eating..."); } }; const Dog = { __proto__: Animal, bark() { console.log("Woof!"); } }; const myDog = Object.create(Dog); myDog.eat(); // logs "Eating..." myDog.bark(); // logs "Woof!"
This approach involves creating a base class constructor function and then extending it by defining a new constructor function that takes the base class constructor as an argument and adds additional properties and methods.
function Animal() { this.eat = function() { console.log("Eating..."); } } function Dog(name) { Animal.call(this); this.name = name; this.bark = function() { console.log("Woof!"); } } const myDog = new Dog("Luna"); myDog.eat(); // logs "Eating..." myDog.bark(); // logs "Woof!"
This approach involves creating a temporary object that inherits from the base class and then uses that object to create the desired subclass. It is similar to prototype-based inheritance, but instead of modifying the__proto__
const Animal = { eat() { console.log("Eating..."); } }; const Dog = (function() { function AnimalProxy() {} AnimalProxy.prototype = Animal; const proxy = new AnimalProxy(); proxy.bark = function() { console.log("Woof!"); } return proxy; })(); const myDog = Object.create(Dog); myDog.eat(); // logs "Eating..." myDog.bark(); // logs "Woof!"
__proto__
property, it creates a new object that acts as a bridge between the base class and the subclass.rrreee
The above is the detailed content of How to implement inheritance in es5. For more information, please follow other related articles on the PHP Chinese website!