Possible Duplicate:
variable hoisting
var a = "global";
//version 1
function changeGlobal(){
alert(a); //why is 'a' undefined here?
if(a){
var a = "local";
alert(a);
}
}
//version 2
function changeGlobal(){
alert(a); //why is 'a' 'global' here? what diff does 'var a="local"' make?
if(a){
//var a = "local";
alert(a);
}
}
changeGlobal();
问题是内联的。帮助我理解变量作用域。
最佳答案
在 JavaScript 中,变量声明被“提升”到函数的顶部,与声明它们的位置无关。
因此,在changeGlobal的第一个变体中,当您声明var a = "local"
时,a
变量声明被提升到顶部。变量的赋值也不会被提升,因此当您警告 a
时,它是一个未赋值的变量,因此未定义。
也就是说,
function changeGlobal(){
alert(a); //why is 'a' undefined here?
if(a){
var a = "local";
alert(a);
}
}
相当于
function changeGlobal(){
var a; // hoisted here (not assigned a value yet)
alert(a); //why is 'a' undefined here?
if(a){
a = "local"; // only assigned a value here
alert(a);
}
}
关于javascript - 局部变量影响全局变量 - Javascript 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13427311/