我认为它们是等价的,但我不确定:
var __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
和
var __extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
child.prototype = parent.prototype;
child.prototype.constructor = child;
child.__super__ = parent.prototype;
return child;
};
答案 0 :(得分:1)
两个函数都使用child
对象的所有属性扩展parent
(函数)对象,并设置__super__
属性。然后差异开始了:
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor;
此代码为child
创建一个继承自parent.prototype
的原型对象。它是old version所做的Object.create()
。这是经典的JavaScript继承模式。
child.prototype = parent.prototype;
child.prototype.constructor = child;
child.__super__ = parent.prototype;
此代码是废话。它将child
的原型对象设置为parent.prototype
,但在下一行中忘记了,现在两个属性都指向同一个对象(child.prototype === parent.prototype
)。因此,parent.prototype.constructor === child
和child.__super__ === child.protoype
- urgh。