2014-06-14 37 views
0

我正在學習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; 
    } 
    }; 
})(); 
+0

http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Jack

回答

1

只要有一個對象的引用,它就不會被垃圾收集。

在JavaScript方面,上面的代碼創建一個閉合,有效地捕集內部函數內的之外的值。

這裏是一個簡短閉合例子:

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. 

較長的討論,請訪問:
How do JavaScript closures work?

0

你是指封閉範圍。 閉包範圍是一個內部函數有,訪問創建範圍的外部函數返回即使一個範圍!

所以,是的,你是正確的,外「私人」功能不會被垃圾收集直到可以訪問它不再是在內存中的內部範圍。