2012-08-17 100 views
0

我不太確定它爲什麼會發生,如果有人能夠向我解釋這是很好的。奇怪的變量範圍問題

所以我得到了下面的代碼:

var text = 'yes'; 
(function f() { 
    alert(text); 
})(); 

而且它會提醒 '是' 符合市場預期。但是,如果我展開它是這樣的:

var text = 'yes'; 
(function f() { 
    alert(text); 
    var text = 'no'; 
})(); 

我非常期待這個提醒「是」太然後覆蓋文本變量在局部範圍內。但相反,它提醒未定義。

這是在當前的Chrome和Firefox中測試,所以這似乎是一個想要的行爲?!

回答

6

變量(和功能)聲明是範圍hoisted to the top。所以你的代碼相當於:

var text = 'yes'; 
(function f() { 
    var text; // shadows the outer variable; initialised with `undefined` 
    alert(text); // still undefined 
    text = 'no'; // now it has the value 'no' 
})(); 
var text = 'yes'; 
(function f() { 
    var text; // shadows the outer variable; initialised with `undefined` 
    alert(text); // still undefined 
    text = 'no'; // now it has the value 'no' 
})(); 
+0

這幾乎是我以爲也是從編譯器的角度思考問題,但它起初有點意外。這是在ECMAScript/Javascript定義中定義的嗎? – bardiir 2012-08-17 12:20:57

+0

是的,你必須通過它。 http://es5.github.com/#x10.4.3,http://es5.github.com/#x10.2.1.1和http://es5.github.com/#x10.5(尤其是這一個)似乎是相關的。 – 2012-08-17 12:24:34

+0

好的謝謝。以後每個人都可以閱讀:稱爲詞法範圍:) – bardiir 2012-08-17 12:28:12

1

您將其聲明爲該範圍內的新變量,因此它不會覆蓋。嘗試:

var text = 'yes'; 
(function f() { 
    alert(text); 
    text = 'no'; 
})(); 

Demo