你能澄清这个 JavaScript 变量提升行为吗?

Can you clarify this JavaScript variable hoisting behavior?

案例 1:

var text = 'outside';
function logIt(){
    console.log(text);
    text ='inside';
}
logIt(); //prints outside. why?

我以为函数logIt()里面的text会被提升到函数顶部打印undefined

案例2:

var text = 'outside';
function logIt(){
    console.log(text);
    var text ='inside';
}
logIt(); //prints undefined

这一个按预期打印 undefined。有人可以解释为什么在 case1 中我们得到值 outside 吗?

因为提升内部变量 text 被移动到函数的开头。但只有它的名称部分:

var text = 'outside';
function logIt(){
    var text;
    console.log(text);
    text ='inside';
}
logIt(); //prints undefined

案例 1 记录 "outside",因为 textlogIt 周围范围内的变量,因此可以在 logIt 内访问。在 console.log 调用之后,您可以按词法重新分配 text。所以不考虑这次重新评估。

提升的是变量 声明,而不是赋值。

在第一个函数中,您仅在 console.log 调用 之后覆盖了 text 的值,而没有覆盖其他 text正在引入函数的本地范围。

在第二种情况下,您 引入了一个新的 text 本地变量(如预期的那样初始化为 undefined),并且由于对于变量提升,实际的 var text 行在 调用 console.log 之前被解释为 ,因此 undefined.

MDN

提升:你可以理解为整个函数体和变量一起放在脚本的顶部 具有未定义的值(如果在分配完成之前使用它们)

现在案例 1:

调用函数时console.log执行时text的值仍然是"outside"

并且在控制台日志后将值更改为 "inside"

如果调用logIt()后立即写console.log,那么会显示"inside"。

var text = 'outside';
function logIt(){
    console.log(text);
    text ='inside';
}
logIt(); //prints outside. why?

案例 2:在这种情况下,您在函数 logIt 中创建一个新变量,然后将其提升为 var text = undefined (因为你在分配之前使用它)

var text = 'outside';
function logIt(){
    console.log(text);
    var text ='inside';
}
logIt(); //prints undefined

这次调用函数后尝试打印console.log(text)。它将打印 "outside in this case as global scope has no effect because of logIt function in this case"