我有下面的程序
Object.prototype.inherit = function(baseConstructor) {
this.prototype = (baseConstructor.prototype);
this.prototype.constructor = this;
};
Object.prototype.method = function(name, func) {
this.prototype[name] = func;
};
function StrangeArray(){}
StrangeArray.inherit(Array);
StrangeArray.method("push", function(value) {
Array.prototype.push.call(this, value);
});
var strange = new StrangeArray();
strange.push(4);
alert(strange);
当 irun 它时我得到堆栈溢出?为什么?
最佳答案
您正在将 StrangeArray.prototype
设置为 Array.prototype
。稍后,您将向 StrangeArray.prototype
添加一个 push
方法(现在与 Array.prototype
相同)。因此,您实际上是在设置 Array.prototype.push
。您的 push
方法调用 Array.prototype.push
- 即它本身。所以它最终只会重复调用自己,然后导致堆栈溢出。
关于javascript - javascript继承中的堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1251229/