javascript函数中的词法作用域

Lexical scope in javascript function

本文关键字:词法 作用域 函数 javascript      更新时间:2023-09-26

以下代码片段:

a = 0;
function f1() {
    a = 1;
    f2();
}
function f2() {
    return a;
}
f1();

返回未定义。

从我的理解,函数访问变量时,他们被定义,并访问这些变量的值时,他们被执行。所以,在这种情况下,我猜f2可以访问全局变量'a',并读取它的修改值(1)。那么为什么它是未定义的?

您没有返回f1函数中调用f2()或其他任何内容的结果,因此f1正确返回undefined

也许你想要的是:

a = 0; // variable a defined in the global scope and set to 0
function f1() {
    a = 1; // since a is declared without var,
           // sets the value of global variable a to 1
    return f2();
}
function f2() {
    return a; // since a was not declared with var,
              // return a from the global scope
}
alert(f1()); // displays the computed value 1 of a

问候。