0

I'm learning about Javascript's module pattern. 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? 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;
    }
  };
})();
Don P
  • 60,113
  • 114
  • 300
  • 432

2 Answers2

1

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.

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?

Community
  • 1
  • 1
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
0

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.

LexJacobs
  • 2,483
  • 15
  • 21