本文討論了 ES5 中的繼承方法,重點在於三種主要方法:基於原型的繼承、構造函數繼承和寄生繼承。文章解釋了每種方法的優點和缺點,提供了程式碼例如
在ES5中,繼承可以透過幾種方法來實現:
這是最最常用常見的方法在ES5 中。它涉及創建一個基類(父類),然後透過創建繼承基類的屬性和方法的新物件來「子類化」它。這是透過操作子類別物件的 __proto__
屬性來完成的。 __proto__
property of the subclass objects.
<code class="javascript">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!"</code>
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.
<code class="javascript">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!"</code>
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__
<code class="javascript">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!"</code>
以上是es5實作繼承的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!