You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于原方法重写JavaScript对象方法并避免栈溢出?

解决方法

你的代码触发栈溢出,是因为重写后的a.method里调用this.method()时,实际上调用的就是这个新重写的函数本身,导致无限递归。要实现预期效果,核心是先保留原方法的引用,再在新方法里调用原方法而非自身。

方案一:用变量缓存原方法

const a = {
  number: 2,
  method() {
    return this.number
  }
}

// 缓存原方法的引用
const originalMethod = a.method;

// 重写method
a.method = function() {
  // 调用原方法时用call绑定this,确保原方法的this指向a
  return 40 + originalMethod.call(this);
}

console.log(a.method()); // 输出42

方案二:将原方法存为对象的私有属性

const a = {
  number: 2,
  method() {
    return this.number
  }
}

// 把原方法存到对象的另一个属性上
a._originalMethod = a.method;

// 重写method
a.method = function() {
  return 40 + this._originalMethod();
}

console.log(a.method()); // 输出42

这两种方式都能避免递归调用,让新方法基于原方法的返回值计算出预期结果42。

内容的提问来源于stack exchange,提问作者Simone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:40:46