2013-10-11 47 views
-1
function setupSomeGlobals() { 
    // Local variable that ends up within closure 

    var num = 666; 
    // Store some references to functions as global variables 
    gAlertNumber = function() {console.log(1); alert(num); } 
    gIncreaseNumber = function() { num++; } 
    gSetNumber = function(x) { num = x; } 
} 

我該如何訪問這裏的gAlertNumber方法?關閉在JavaScript瞭解示例

更新:這個代碼是實施例4中關於How do JavaScript closures work?

+0

你不能在函數之外訪問它,因爲它不在範圍之內,並且你沒有可訪問的引用 – musefan

+4

@Jeffman,@musefan:'gAlertNumber'是一個全局變量。爲什麼你認爲它不能在'setupSomeGlobals'之外訪問? [小提琴](http://jsfiddle.net/j5yTn/) – Andreas

+3

這是一個不錯的方法來初始化的全局變量,你真的不應該反正使用全局變量。在「嚴格」模式下,這將是一個錯誤。 – Pointy

回答

1

假設你在Web瀏覽器的時候,你必須先執行setupSomeGlobal()。 那麼你的非聲明的處理變量g^...將全局對象window下創建,你就可以從任何地方在你的頁面執行gAlertNumber()

你可以在執行setupSomeGlobal()人體的onload

<html> 
    <head> 
     <script> 
      function setupSomeGlobals() { 
       // Local variable that ends up within closure 

       var num = 666; 
       // Store some references to functions as global variables 
       gAlertNumber = function() {console.log(1); alert(num); } 
       gIncreaseNumber = function() { num++; } 
       gSetNumber = function(x) { num = x; } 
      } 
     </script> 
    </head> 

    <body onload="setupSomeGlobals();"> 
     <input type="button" value="Show me more or less the number of the beast" onclick="gAlertNumber();" 
    </body> 
</html> 

這就是說,你設立「全球性」功能的方法是不是很漂亮。 例如,我非常喜歡描述here的模式。

0

這裏答案是一個例子,

(function() { 
    console.log(1); 
    // Local variable that ends up within closure 
    var num = 666; 
    var sayAlert = function() { console.log(num); } 
    num++; 
    return sayAlert(); 
})(); 

這將定義之後立即調用。

與您的代碼

所以,

function setupSomeGlobals() { 

    var num = 666; 
    // Store some references to functions as global variables 
    gAlertNumber = function() {console.log(1); alert(num); } 
    gIncreaseNumber = function() { num++; } 
    gSetNumber = function(x) { num = x; } 

    gAlertNumber(); 

} 
setupSomeGlobals(); 

在這裏,你可以調用子功能gAlertNumber()父功能setupSomeGlobals()內,你不能在父函數外部訪問它。

但是你可以調用父函數之後調用此,這意味着不調用gAlertNumber()父函數內。把它調用父等之後,

function setupSomeGlobals() { 
    // Local variable that ends up within closure 
    var num = 666; 
    // Store some references to functions as global variables 
    gAlertNumber = function() {console.log(1); alert(num); } 
    gIncreaseNumber = function() { num++; } 
    gSetNumber = function(x) { num = x; } 
} 

setupSomeGlobals(); 
gAlertNumber(); 
+0

來訪問它,我沒有得到我從這裏得到的第二個答案的示例http://stackoverflow.com/questions/ 111102/how-do-javascript-closures-work?rq = 1這裏沒有var – user2114177

+0

,如果我們寫'gAlertNumber();像你建議我們可以做什麼 gIncreaseNumber? – user2114177

+0

@Pointy你是指什麼原因? – devo

0

返回從setSomeGlobals對象()包含三種方法。通過這個對象,你將能夠訪問感興趣的函數並操作num並保持它的狀態,但是你將不能直接訪問num。這被稱爲模塊模式,即閉包的應用。

0

嗯,這將在瀏覽器中運行

gAlertNumber被視爲呼籲

window.gAlertNumber() 
setSomeGlobals內

所以分配函數對象未定義的窗口是窗口屬性..這將是相同的屬性。比你接近局部變量NUM這已經是內部窗口對象創建的對象中。因此你可以從窗口範圍訪問它。