javascript继承中的堆栈溢出

rav*_*avi 1 javascript stack-overflow

我有以下编程

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);
Run Code Online (Sandbox Code Playgroud)

当irun它我得到堆栈溢出?为什么?

Jon*_*ght 6

你正准备StrangeArray.prototypeArray.prototype.之后,您将添加一个push方法StrangeArray.prototype(现在与之相同Array.prototype).所以你有效地设置Array.prototype.push.你的push方法调用Array.prototype.push- 即自己.所以它最终只是反复调用自己,你得到一个堆栈溢出.