javascript关闭的混乱

Dan*_*hen 0 javascript closures

我已被证明我并不真正理解javascript封闭,我对以下代码感到困惑.我以为fxn会访问外部foo,但它实际上打印出"underfined".为什么??

var foo = "hello";
function fxn(){
   alert(foo);
   var foo = "test"
}

fxn();
Run Code Online (Sandbox Code Playgroud)

Mor*_*ler 6

这是因为在JavaScript中,变量会被提升,这意味着

变量在创建时初始化为未定义.具有Initialiser变量执行VariableStatement时被赋予其AssignmentExpression的值,而不是在创建变量时.(ES5§12.2)

因此,从语义上讲,您的代码将等同于以下内容......

var foo = "hello";
function fxn(){
   var foo; //Variables are initialised to undefined when created
   alert(foo);
   foo = "test"; //A variable with an *Initialiser* is assigned the value of its *AssignmentExpression* when the *VariableStatement* is **executed**
}

fxn();
Run Code Online (Sandbox Code Playgroud)