奇怪的变量范围问题

bar*_*iir 0 javascript scope

我不太确定它为什么会发生,如果有人能向我解释这一点会很棒.

所以我得到以下代码:

var text = 'yes';
(function f() {
    alert(text);
})();
Run Code Online (Sandbox Code Playgroud)

它按预期警告"是".但如果我像这样展开它:

var text = 'yes';
(function f() {
    alert(text);
    var text = 'no';
})();
Run Code Online (Sandbox Code Playgroud)

我非常希望这也能提醒'是'然后覆盖本地范围内的文本变量.但相反,它提醒未定义.

这是在当前的Chrome和Firefox中测试的,所以这似乎是一种想要的行为?!

Fel*_*ing 6

变量(和函数)声明被提升到范围的顶部.所以你的代码相当于:

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'
})();
Run Code Online (Sandbox Code Playgroud)