JS模块模式-为什么私有变量不被删除

JS module pattern - why are private variables not deleted

本文关键字:变量 删除 模块 模式 为什么 JS      更新时间:2023-09-26

我正在学习Javascript的模块模式。下面是一个"basket"模块的例子。

我想我明白这是一个匿名函数,所以你不能访问它的变量,只能访问它的返回值。为什么这个函数中的变量和函数在匿名函数完成执行后没有被删除/垃圾收集?JS如何知道将它们保存在内存中以供以后使用?是因为我们返回了一个可以访问它们的函数吗?

var basketModule = (function () {
  // privates
  var basket = [];
  function doSomethingPrivate() {
    //...
  }
  function doSomethingElsePrivate() {
    //...
  }
  // Return an object exposed to the public
  return {
    // Add items to our basket
    addItem: function( values ) {
      basket.push(values);
    },
    // Get the count of items in the basket
    getItemCount: function () {
      return basket.length;
    },
    // Public alias to a  private function
    doSomething: doSomethingPrivate,
    // Get the total value of items in the basket
    getTotal: function () {
      var q = this.getItemCount(),
          p = 0;
      while (q--) {
        p += basket[q].price;
      }
      return p;
    }
  };
})();

只要存在对对象的引用,它就不会被垃圾收集。

在JavaScript术语中,上面的代码创建了一个Closure,有效地将外部值捕获在内部函数中。

下面是一个简短的闭包示例:

var test = (function() {
  var k = {};
  return function() {
    // This `k` is trapped -- closed over -- from the outside function and will
    // survive until we get rid of the function holding it.
    alert(typeof k);
  }
}());
test();
test = null;
// K is now freed to garbage collect, but no way to reach it to prove that it did.

更详细的讨论在这里:
JavaScript闭包是如何工作的?

您指的是闭包作用域。闭包作用域是内部函数可以访问的作用域,即使在创建该作用域的外部函数返回之后也是如此!

所以,是的,你是正确的,外部'private'函数将不会被垃圾收集,直到访问它的内部作用域不再在内存中。