【发布时间】:2012-04-17 23:51:01
【问题描述】:
我正在使用从 Backbone 改编的扩展函数(除了一些更改以符合我的雇主的命名约定外,其他相同)来实现原型继承。设置以下结构后(下面非常简化),我得到了一个无限循环。
Graph = function () {};
Graph.extend = myExtendFunction;
Graph.prototype = {
generateScale: function () {
//do stuff
}
}
// base class defined elsewhere
UsageGraph = Graph.extend({
generateScale: function () {
this.constructor._super.generateScale.call(this); // run the parent's method
//do additional stuff
}
})
ExcessiveUsageGraph = Graph.extend({
// some methods, not including generateScale, which is inherited directly from Usage Graph
})
var EUG = new ExcessiveUsageGraph();
EUG.generateScale(); // infinite loop
循环正在发生,因为ExcessiveUsageGraph 将原型链上升到UsageGraph 以运行该方法,但this 仍设置为ExcessiveUsageGraph 的实例,因此当我使用this.constructor._super 运行父级时方法它也会在链上更上一层到UsageGraph 并再次调用相同的方法。
如何从 Backbone 样式的原型中引用父方法并避免这种循环。如果可能,我还想避免按名称引用父类。
编辑 Here's a fiddle demonstrating that this happens in Backbone
【问题讨论】:
标签: javascript inheritance backbone.js prototypal-inheritance