JavaScript函数中的词法作用域,为什么代码返回未定义

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?

1个回答

3

这是因为 JavaScript 中存在变量提升(hoisting)机制,你在函数内声明的变量会被提升到所属作用域的顶部,所以实际上你的代码看起来像这样:

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

如果你只是想改变外部的变量,那么去掉var关键字即可,因为它声明了一个新的局部变量。
var variable = "top level " ;

function outer(){

    alert(variable);

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

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

outer();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接