为什么即使稍后在代码中定义了局部变量,全局变量也无法访问 [英] why is global variable not accessible even if local variable is defined later in code
本文介绍了为什么即使稍后在代码中定义了局部变量,全局变量也无法访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么以下代码段会生成以下输出?
why does the following code segment generate the following output?
代码段:
var a = 10;
function(){
console.log(a);
var a = 5;
}
输出:
undefined
推荐答案
由于变量位于顶部,因此在函数中已声明变量var a = 5,该变量与以下变量相同:
Because variable is hoisted at top and in your function you have declared the variable var a = 5 which is same as following:
var a = 10;
function(){
var a; // a = undefined
console.log(a);//a is not defined so outputs undefined
a = 5;
console.log(a);//a is now 5 so outputs 5
}
并且在您的函数范围中声明了var,它看不到全局变量,而是局部变量,即var a且未定义.
And in your function scope var is being declared it doesn't see global variable but local variable i.e. var a and which is undefined.
这篇关于为什么即使稍后在代码中定义了局部变量,全局变量也无法访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文