【发布时间】:2018-02-14 03:16:15
【问题描述】:
我对 JavaScript 的原型继承非常了解,但我不会说它是完美的。我正在研究 JavaScript 继承的最新原型语法,到目前为止它很有意义。
__proto__ 用于查找父函数的prototype。假设我有Cat 和Mammal,我可以简单地将Cat.prototype.__proto__ 指向Mammal.prototype。
ChildClass.prototype.__proto__ = ParentClass.prototype;
ChildClass.prototype.constructor = ChildClass;
强烈反对使用__proto__,因为它直到最近才标准化。因此,现代标准化做法是使用Object.create
ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;
现在让我们看看 ES5 的代理方法
function Surrogate() {};
Surrogate.prototype = ParentClass.prototype;
ChildClass.prototype = new Surrogate();
ChildClass.prototype.constructor = ChildClass;
显然,
ChildClass.prototype = ParentClass.prototype;
不好,因为修改 ChildClass 的原型也会修改 ParentClass 的原型。
但是为什么我们不能这样做呢?
ChildClass.prototype = new ParentClass();
为什么我们需要一个代理?
【问题讨论】:
-
我个人认为您的
ES5's surrogate approach并不完全准确。Object.create在 2011 年被添加到5.1中,所以就现代 JS 而言,它已经存在了很长时间。 -
new被使用之前 ES5 引入Object.create。
标签: javascript ecmascript-5 prototypal-inheritance