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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:17:47