Function - Issue with scope and closures in JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

My question is really more about scope in JavaScript, rather then closures.

Let s take the following code:

var f = function () {
    var n = 0;
    return function () {
        return n++;
    };
}();

console.log(f());
console.log(f());

The above code outputs:

0
1

As you can see from the above code, f (self-invoked) returns a function, creating a closure of n.


So, it works with an anonymous function; thus, I then tried it with a named function:

var f2 = function () {
    return n++;
};

var f = function () {
    var n = 0;
    return f2;
}();

console.log(f2()); // <= [n is not defined]

The above code doesn t work, with the error n is not defined. I assume that this is a scoping issue; but I cannot figure why exactly;

Why is it that the scope is the same with an anonymous, inner function but does not work with a named, outer function?

Also, in the second example, am I creating a closure?

Answers

The closure is created in the first example because the code in the anonymous function uses a local variable that is declared outside of the anonymous function.

In the second example the scope of the n variable in the function f2 is already decided when the function is declared. Creating a local variable with the same name doesn t change the meaning of the function, and using the function inside another function doesn t change it s scope. Thus, the function doesn t use the local variable.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/1782265/issue-with-scope-and-closures-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils