函数和变量提升的意外结果
unexpected results with function and variable hoisting
我正在阅读该系列的第二本书 "You don't know JS" 并且我已经 read that 在变量之前提升了函数。
所以这是代码:
foo(); // 1
var foo;
function foo() {
console.log( 1 );
}
foo = function() {
console.log( 2 );
};
这将输出 1。但为什么呢?首先提升函数,然后提升变量。因此,在我的函数 foo(打印 1 的函数)被提升后,它后面必须跟有变量 foo。所以结果应该是 "undefined" 而不是 "1".
我希望代码表现得像:
// hoisted first
function foo() {
console.log( 1 );
}
// hoisted second
var foo; // implicitly initialized to 'undefined'
foo(); // call 'undefined' - error?
foo = function() {
console.log( 2 );
};
这里发生了什么?
如前所述,函数在变量之前被提升;如果解释器遇到var foo
after foo
has already been defined in the scope,它将被简单地忽略。它不会将 foo
分配给 undefined
,它只会确保当前范围内存在名为 foo
的变量 - 它已经存在。
正如你所不知道的 JS link:
multiple/duplicate var declarations are effectively ignored
这是另一个常见的提升重复变量被忽略的例子,可能更多 familiar/intuitive:
if (false)
var foo = false;
else
var foo = true;
变成
var foo;
var foo; // does not actually do anything; does not assign `undefined` to `foo`, ignored
// foo just *happens* to not have anything assigned to it in almost all cases like this
if (false)
foo = false;
else
foo = true;
我正在阅读该系列的第二本书 "You don't know JS" 并且我已经 read that 在变量之前提升了函数。
所以这是代码:
foo(); // 1
var foo;
function foo() {
console.log( 1 );
}
foo = function() {
console.log( 2 );
};
这将输出 1。但为什么呢?首先提升函数,然后提升变量。因此,在我的函数 foo(打印 1 的函数)被提升后,它后面必须跟有变量 foo。所以结果应该是 "undefined" 而不是 "1".
我希望代码表现得像:
// hoisted first
function foo() {
console.log( 1 );
}
// hoisted second
var foo; // implicitly initialized to 'undefined'
foo(); // call 'undefined' - error?
foo = function() {
console.log( 2 );
};
这里发生了什么?
如前所述,函数在变量之前被提升;如果解释器遇到var foo
after foo
has already been defined in the scope,它将被简单地忽略。它不会将 foo
分配给 undefined
,它只会确保当前范围内存在名为 foo
的变量 - 它已经存在。
正如你所不知道的 JS link:
multiple/duplicate var declarations are effectively ignored
这是另一个常见的提升重复变量被忽略的例子,可能更多 familiar/intuitive:
if (false)
var foo = false;
else
var foo = true;
变成
var foo;
var foo; // does not actually do anything; does not assign `undefined` to `foo`, ignored
// foo just *happens* to not have anything assigned to it in almost all cases like this
if (false)
foo = false;
else
foo = true;