2012-08-17 129 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