Domanda

The following snippet:

a = 0;

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

function f2() {
    return a;
}

f1();

returns undefined.

From what I understand, functions get access to variables when they're defined, and access the values of those variables when they're being executed. So, in this case I would've guessed f2 to have access to the global variable 'a', and read it's modified value (1). So why is it undefined?

È stato utile?

Soluzione

You're not returning the result of the invocation of f2(), or anything else, in the f1 function, so f1 is correctly returning undefined.

Altri suggerimenti

Perhaps what you were after was the following:

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

Regards.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top