2012-02-22 61 views
0

我發現自己的Javascript的變量範圍,有人可以向我解釋爲什麼第一個示例不起作用,但第二個呢?由Javascript的變量範圍迷惑

function test() { 
    return typeof(the_variable) !== 'undefined' && the_variable; 
} 

(function() { 
    var the_variable = "doesn't work"; 
    console.log(test()); 
}()); 

var the_variable = "does work"; 
console.log(test()); 

輸出我在日誌中得到:

false 
does work 

我也想知道怎麼做類似於第一個例子中的東西,

乾杯,戴夫。

回答

6

解釋評論:

function test() { 
    return typeof(the_variable) !== 'undefined' && the_variable; 
} 

// The variable in this function is scoped to the anonymous function. 
// It doesn't exist outside that function, so `test` cannot see it 
(function() { 
    var the_variable = "doesn't work"; 
    console.log(test()); 
}()); 

// This variable exists in a scope that wraps the `test` function, so it can see it. 
var the_variable = "does work"; 
console.log(test()); 
+0

但測試函數被調用匿名函數的範圍內,爲什麼不能測試看到匿名函數的範圍裏面的東西? – kzar 2012-02-22 17:26:24

+0

更明確地說,把'var foo'放在一個範圍內的任何地方都完全等同於把它作爲範圍內的第一項。 – gsnedders 2012-02-22 17:27:31

+2

@kzar因爲它不是調用鏈範圍,所以它是詞法範圍。 – gsnedders 2012-02-22 17:28:05

0

在JavaScript中,函數定義範圍。在您的第一個示例中,the_variable不在test的範圍之內。另一方面,在第二個示例中,the_variable在全局範圍內定義並且在任何地方都可用。

編輯

捕捉the_variable在閉合,如果你希望它是提供給test

var foo = (function() { 
    var the_variable = "does work"; 
    function test() { 
     return typeof(the_variable) !== 'undefined' && the_variable; 
    } 
    return {test : test}; 
}()); 
console.log(foo.test()); 

輸出:

確實工作

+0

對,但如果我從另一個函數內調用一個函數,爲什麼調用的函數不能訪問它被調用的地方? – kzar 2012-02-22 17:29:45

+0

'function test()'打開一個新的範圍。來自封閉匿名函數的'var'將不可用。如果可用,則在閉包中捕獲'the_variable'。 – 2012-02-22 17:40:18

+0

很酷的主意,但我不能在閉包內定義test()函數,閉包實際上是在一個單獨的文件中定義的。 – kzar 2012-02-22 17:47:09