我已被证明我并不真正理解javascript闭包,并且我对以下代码感到困惑。我以为 fxn 会访问外部 foo,但它实际上打印出“underfined”。为什么??
var foo = "hello";
function fxn(){
alert(foo);
var foo = "test"
}
fxn();
最佳答案
这是因为在 JavaScript 中,变量得到 hoisted ,这意味着
Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.(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();
关于javascript - javascript 闭包的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21677208/