3
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 ?

4

1 回答 1

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();

如果您只想更改 outside variable,请删除var关键字,因为它声明了一个新的局部变量

var variable = "top level " ;

function outer(){

    alert(variable);

    variable = " inside outer, outside inner"; // no "var"

    function inner(){
        alert(variable);
    }
    inner();
}

outer();
于 2014-08-01T05:51:10.833 回答