如何基于原方法重写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
相关产品推荐
相关产品推荐

