【问题标题】:Lexical scope in javascript functionjavascript函数中的词法范围
【发布时间】:2013-05-26 21:22:43
【问题描述】:

下面的sn-p:

a = 0;

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

function f2() {
    return a;
}

f1();

返回未定义。

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

【问题讨论】:

  • f2 中的return 不会从f1 返回...但是是的,所有三个as 都引用同一个全局变量。

标签: javascript scope closures lexical-scope


【解决方案1】:

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

【讨论】:

  • 好收获!该函数获取其主体返回的值,但它仍然必须将其返回给它的调用者。
【解决方案2】:

也许你所追求的是:

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

问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多