javascript函数中的词法作用域,为什么代码返回undefined ?

Lexical Scoping in javascript function, why is the code returning undefined

本文关键字:代码 为什么 返回 undefined 作用域 函数 词法 javascript      更新时间:2023-09-26
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呢?

这是因为提升,你在函数内声明的变量被提升到它所在作用域的顶部,所以你的代码看起来像这样

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