自调用匿名函数是否会在 运行 之后收集垃圾?

Does self invoking anonymous function get garbage collected after it run once?

(function (){
  let x = "hy"; 
   console.log(x);
})()

所以问题是这个函数执行后是否会被垃圾收集并从内存中删除并释放内存?

被调用的函数表达式将被垃圾回收,但不会在函数运行后立即被回收——它只会在下一次GC 运行,这可能需要几秒钟。 (此操作大部分对 JavaScript 不可见,但并非完全不可见,如果您使用新的 WeakRef,请参阅代码片段)

const weakRef = (function (){
  // This fn below is the one we'll be examining to see when it gets GCd
  // It's not the IIFE but the behavior is probably similar enough
  const fn = () => {
    let x = "hy"; 
    console.log(x);
  };
  fn();
  return new WeakRef(fn);
})();

const t0 = Date.now();
const intervalId = setInterval(() => {
  const hasGcd = weakRef.deref() === undefined;
  console.log('hasGcd:', hasGcd, Date.now() - t0);
  if (hasGcd) {
    clearInterval(intervalId);
  }
}, 200);

x 标识符也将被 GC,但有一个复杂的问题:记录的表达式,因为它被记录,仍然可以存在(至少只要控制台存在并且不存在)清除 - 这可能取决于实施)。如果您创建了一个对象并将其记录下来,则该对象可能要等到页面刷新后才会被 GC。