【发布时间】:2014-09-02 04:05:15
【问题描述】:
我从 coffeescript 中找到并改编了一个 JavaScript“类”扩展函数:
var extend = (function() {
var hasProp = Object.prototype.hasOwnProperty;
function ctor(child) {
this.constructor = child;
}
return function(child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key)) {
child[key] = parent[key];
}
}
ctor.prototype = parent.prototype;
child.prototype = new ctor(child);
child.__super__ = parent.prototype;
// child.prototype.__super__ = parent.prototype; // better?
return child;
};
})();
我想知道,他们使用 child.__super__ 而不是 child.prototype.__super__ 是否有原因(请参阅注释掉的代码行)。
我更喜欢注释掉的版本,因为:
您可以通过
this.__super__.propertyName而不是ClassName.__super__.propertyName访问超级属性。所以你在类命名上没有冗余。这对于嵌套继承更有意义,因为您可以使用
this.__super__.__super__.propertyName而不是ClassName.__super__.constructor.__super__.propertyName
我看不出有什么原因,但您甚至可以像这样以“静态”方式调用“静态”函数:
ClassName.prototype.__super__.constructor.staticMethod()
我的版本是否有我可能忽略的缺点?
编辑:我将行更正为var hasProp = Object.prototype.hasOwnProperty;
【问题讨论】:
-
你在哪里“找到”了这个?是来自 CoffeeScript 生成的代码吗?
-
没错,但我稍微改了一下。
标签: javascript inheritance coffeescript