gpt4 book ai didi

javascript - “提升”JavaScript 变量

转载 作者:IT王子 更新时间:2023-10-29 03:19:03 24 4
gpt4 key购买 nike

我不完全理解为什么以下内容在最后显示“已提升”。

var x = 'set';
var y = function ()
{
// WHAT YOU DON'T SEE -> var x;
// is effectively "hoisted" to this line!

if (!x)
{
// You might expect the variable to be populated at this point...it is not
// though, so this block executes
var x = 'hoisted';
}

alert(x);
}

//... and this call causes an alert to display "hoisted"
y();

如有任何指点,我们将不胜感激。

最佳答案

引用 MDN Docs on var hoisting ,

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

因此,在您的情况下,JavaScript 知道一个局部变量(不是在外部声明的那个) x 是在函数的某处定义的,但它不知道它的实际值,直到执行到达分配给 x 的赋值语句。 (声明在编译时处理,赋值在执行时完成)直到赋值完成,将使用默认值undefined。自 undefined is falsy , 条件

if (!x) {

满足并执行赋值语句。这就是您在警告框中被提升的原因。


假设您没有在函数内部声明 x

var x;

var y = function () {
if (!x) {
x = 'hoisted';
}
alert(x);
}

y();
alert(x);

这里,由于 x 没有在函数内的任何地方声明,在运行时,JavaScript 将在更高的范围内寻找 x。在这种情况下,它会在函数外部找到它。因此,将使用 x。由于您将 hoisted 分配给 x,因此内部 alert 也会显示 hoisted 并且在离开函数后,alert(x) 也会提醒 hoisted

关于javascript - “提升”JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29667199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com