简体   繁体   English

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

[英]JS module pattern - why are private variables not deleted

I'm learning about Javascript's module pattern. 我正在学习Javascript的模块模式。 Below is an example of a "basket" module. 以下是“购物篮”模块的示例。

I think I understand that this is an anonymous function that executes, so you can't access variables within it, only what it returns. 我想我知道这是一个执行的匿名函数,因此您无法访问其中的变量,只能访问它返回的变量。 Why are the variables and functions within this function not deleted / garbage collected after the anonymous function finishes executing? 为什么匿名函数完成执行后,该函数中的变量和函数没有被删除/垃圾回收? How does JS know to keep them in memory for later use? JS如何知道将它们保留在内存中以备后用? Is it because we've returned a function which will access them? 是因为我们返回了可以访问它们的函数吗?

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;
    }
  };
})();

As long as there is a reference to an object, it will not be garbage collected. 只要有对对象的引用,就不会对其进行垃圾回收。

In JavaScript terms, the above code creates a Closure, effectively trapping the outside values inside the inner functions. 用JavaScript术语,上面的代码创建一个Closure,有效地将外部值捕获在内部函数中。

Here is a short closure example: 这是一个简短的关闭示例:

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.

A longer discussion is available here: 可在此处进行更长的讨论:
How do JavaScript closures work? JavaScript闭包如何工作?

You are referring to closure scopes. 您指的是闭包范围。 A closure scope is a scope that an inner function has access to, even after the outer function that created the scope has returned ! 闭包范围是内部函数可以访问的范围, 即使在创建该范围的外部函数返回后也是如此

So, yes, you are correct, the outer 'private' function will not be garbage collected until the inner scope that has access to it is no longer in memory. 因此,是的,您是对的, 除非可以访问内部作用域的内部范围不再在内存中,否则不会对外部“私有”功能进行垃圾收集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM