javascript - javascript 闭包的困惑

标签 javascript closures

我已被证明我并不真正理解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/

相关文章:

c# - for 和 foreach 在闭包方面有什么区别

javascript - 相同的 JS 闭环问题 - 但 SO 的答案不起作用

javascript - 如何使 CoffeeScript 闭包感知非局部变量?

javascript - 使用闭包创建我自己的 console.log 版本 | Javascript

javascript - JS/ES6 : Undefined check on destructuring on a dynamic defined variable

javascript - 是否每次需要 token 时都需要调用 acquireTokenSilent?

javascript - 从对象数组构造元素数组?

javascript - JS Closure 的变量值

javascript - 使文本 "more"可选

javascript - for in 循环只使用最后一个属性