var variable = "top level " ;
function outer(){
alert(variable); // why does this alert returns undefined ??
var variable = " inside outer, outside inner";
function inner(){
alert(variable);
}
inner();
}
outer();
我从词法范围的定义中理解的是,函数可以访问其范围内和范围之上的所有值,即在它们之前定义的所有值。那么为什么第一个警报返回undefined?
答案 0 :(得分:3)
由于提升,你在函数中声明的变量被提升到它所在范围的顶部,所以你的代码看起来真的像这样
var variable = "top level " ;
function outer(){
var variable; // undefined, a new local variable is declared, but not defined
alert(variable); // alerts undefined, as that's what the variable is
variable = " inside outer, outside inner";
function inner(){
alert(variable);
}
inner();
}
outer();
如果您只是想更改外部variable
,请删除var
关键字,因为它声明了一个新的局部变量
var variable = "top level " ;
function outer(){
alert(variable);
variable = " inside outer, outside inner"; // no "var"
function inner(){
alert(variable);
}
inner();
}
outer();