2013-10-11 48 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这已经是内部窗口对象创建的对象中。因此你可以从窗口范围访问它。