1

谁能向我解释为什么if里面的语句bar没有foo定义?

var foo = 1;
function bar() {
    if (!foo) {
        var foo = 10;
    }
    alert(foo);
}
bar();
4

2 回答 2

2
// This foo is at the global level.
var foo = 1;
function bar() {
  // the compiler puts in this line:
    var foo;
    if (!foo) {
        // and the var here doesn't matter.
        foo = 10;
    }
    alert(foo);
}
bar();
于 2014-07-16T00:44:00.477 回答
2

给定的代码将被解析如下:

var foo = 1;
function bar() {
    var foo;
    if (!foo) {
        foo = 10;
    }
    alert(foo);
}
bar();

本地 foo 被提升到函数的顶部,因为 JS 只有函数作用域,没有块作用域。“提升”变量将优先于函数外部定义的 foo,这就是为什么在 if 语句中未定义变量的原因。

于 2014-07-16T00:44:29.433 回答