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