JavaScript中如何删除动态生成函数?避免内存泄漏
动态生成函数引发内存泄漏疑问及优化需求
arr.map(v => { v[0] = new Function(` try { if (${v[1]?.before}) { let func = ${v[0]}; const rtn = func.call(this, this); // call function passed before deconstruction of tooltip func = undefined; this?.tooltip?.deconstruct(${misc?.fadeOut}); // deconstruction of tooltip return rtn; } else { this?.tooltip?.deconstruct(${misc?.fadeOut}); // deconstruction of tooltip let func = ${v[0]}; const rtn = func.call(this, this); // call function passed after deconstruction of tooltip func = undefined; return rtn; } } catch(err) { return console.error(err); // TODO: remove in production } `); const bounded = v[0].bind(this); // bind tooltip to function so this.tooltip.deconstruction can be called v[0] = undefined; return [ bounded, v[1], v[2] ]; });
背景说明
这段代码用于为事件监听器生成包装函数,调用时会销毁关联的tooltip。其中:
v[0]始终是一个函数v[1]提供该函数的处理信息v[2]和misc可忽略
但每次执行这段代码时,VS Code的加载脚本中都会出现大量新生成的函数(运行片刻后会产生一堆eval函数),担心会造成内存泄漏。
已尝试的解决方案
- 用
argument.callee尝试删除函数 - 在移除事件监听器时做清理操作
但这些操作仅作用于局部作用域,无法将动态生成的函数从加载脚本中移除。
需求
想了解是否有办法彻底删除这些动态生成的函数,或者是否需要改写代码从根源上避免这个问题。
内容的提问来源于stack exchange,提问作者LuniZunie
相关产品推荐
相关产品推荐

