function f1(){
var n=999;
function f2(){
alert(n); // 999
}
}
is the function f2() a closure? if not? why?
but in this post. How do JavaScript closures work?
why it says:
function foo(x) {
var tmp = 3;
function bar(y) {
alert(x + y + (++tmp));
}
bar(10);
}
foo(2)
That is not a closure.A closure is when you return the inner function. The inner function will close-over the variables of foo before leaving. why?
but i don’t know what’s the difference between the example i made and another i cited, one is not a closure.but one is. i think the two example is the same.
Yes,
f2is a closure, since it accesses a variable (n) from an outer scope. (OK, it’s not really a closure — see update below).nwas declared insidef1, notf2; this makes it belong tof1‘s scope. So when you create the functionf2which referencesn, it is a closure by definition, since it uses someone else’s variable.UPDATE
Alright, if I understand the answer you’ve linked to correctly, it says that
f2is not a closure because it is merely accessing a variable within its scope (just like anifstatement, which gets its own scope within the braces*, can use variables from the outer scope without needing a closure).* Update: Turns out that only functions get their own scope in Javascript, not any old blocks. But my point still stands…
However,
f2would become a closure if it leftf1‘s scope (e.g. by being returned); in that case, it would still have access tof1‘s variablen, even thoughf1‘s original scope would no longer exist (it’s exited when control leaves the function).f2would have “closed over”f1‘s variables, thus artificially extending the lifespan off1‘s scope.Personally, I would still call
f2a closure, even if it never leavesf1. If a function can become a closure simply by being used outside of its declaring scope, and its behaviour inside that scope is no different whether it’s technically a closure or not, then I see no point in making a distinction. I would even go so far as to say that it’s an implementation detail whetherf2is a closure or not, if it never leavesf1‘s scope.On the other hand, ignoring that distinction would mean that any function that uses a global variable would be called a “closure”, since it accesses a variable from an outer scope. So the fact that it becomes a closure only when it leaves the scope(s) that the variables it is using are defined in is a worthwhile (albeit subtle) distinction.
I guess the clearest answer I can give is that it’s not a closure yet.