可变提升 - “var”在函数中使用全局变量名称 [英] Variable hoisting - "var" with global variable name in function
问题描述
我正在练习一些场景并找到一个案例:
I was practicing some scenario and find a case:
根据关闭栏功能应该可以访问 var x
所以我由于 if(!1)
,预计会发出警报1并且条件变为假,但它会提醒 undefined
并且条件变为真,第二个警报值为10.
According to closure bar function should have access to var x
so I expected to alert 1 and condition get false due to if(!1)
but it alerted undefined
and condition get true and second alert is with value 10.
var x = 1;
function bar() {
alert(x);
if (!x) {
var x = 10;
}
alert(x);
}
bar();
所以我很困惑为什么它会提示未定义?
So I am confused why it is prompting undefined?
根据特定范围内的提升,您可以在任何位置始终定义变量。
According to hoisting in a particular scope you define a variable anywhere it is considered as defined at top always.
如果是由于提升效应,它仍然需要提醒10而不是未定义。
If it is due to hoisting effect it still have to alert 10 instead of undefined.
推荐答案
提升将使您的代码有效工作像这样:
Hoisting will make your code effectively work like this:
var x;
x = 1;
function bar() {
var x; //same as var x = undefined;
alert(x);
if (!x) {
x = 10;
}
alert(x);
}
bar();
这篇关于可变提升 - “var”在函数中使用全局变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!