javascript - javascript继承中的堆栈溢出

标签 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);

当 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/

相关文章:

javascript - npm 将所有依赖项和子依赖项放在同一个文件夹中

assembly - 编程语言是否有可能自信地防止堆栈溢出时的未定义行为?

c++ - 我的快速排序代码溢出堆栈

java - 从另一个类的 Gui 类调用 print Text 方法

javascript - 来自 localhost 的 Visual Studio 动态 javascript 引用智能感知

javascript - 蒙哥错误: failed to connect to server [localhost:27017]

javascript - 在 js 中设置 twig 变量 - Symfony 3.4 - JS

java - 在应用程序执行期间显示 JVM 的 ThreadStackSize

java - 如何在递归中避免 StackOverFlow?

javascript - "selectbox"表格点击行后的下拉列表