我正在學習Javascript的模塊模式。以下是「籃子」模塊的示例。JS模塊模式 - 爲什麼不刪除私有變量
我想我明白這是一個執行的匿名函數,所以你不能訪問它內部的變量,只能返回它的內容。爲什麼匿名函數完成執行後,該函數中的變量和函數不會被刪除/垃圾回收? 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;
}
};
})();
http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Jack