本文讨论了 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中文网其他相关文章!