runeveryday — 2011-06-28T07:27:51-04:00 — #1
alert(n); // 999
is the function f2() a closure? if not? why?
what's and use of a closure.could you depict it in your own words. thank you
paul_wilkins — 2011-06-28T17:44:33-04:00 — #2
It's not a closure. It's just a function declaration.
If the f1 function returned a reference to the f2 function, that returned f2 function will then form a closure over the variables from the f1 function.
Here's the best explanation of closure that I've come across.
runeveryday — 2011-06-29T21:13:04-04:00 — #3
your mean that if i call the f1(). then f2() will be a closure?
a closure will form if a function B in a function A. and function A is called. then function B is a closure. am i right? thank you.
paul_wilkins — 2011-06-29T22:03:08-04:00 — #4
No, it won't. It would only be a closure if the f1 function returned a reference to the f2 function.
felgall — 2011-06-29T22:06:07-04:00 — #5
No. The closure would be on the variable "n" but only if the f1 function returned the f2 functon so that f2 can be called after f1 has already finished running (and where the "n" variable would have already gone out of scope except for the fact that there is still a way to reference it via f2.
The following would be a closure:
alert(n); // 999
a = f1();
With that code the last line a() will run the alert to display the 999 even though the call to f1 completed and n would have gone out of scope except for the closure.
runeveryday — 2011-06-30T07:45:24-04:00 — #6
felgall， your mean a closure will be:fuction B in function A. and in function A. there must be fuction B. then to function A's variable. fuction B is a closure. am i right?
runeveryday — 2011-06-30T08:49:53-04:00 — #7
felgall. to sum it up. according to your answer. the benefit of the closure is if outside the function. i can use the closure(f2) to reference the variable(on the above is n). am i right?thank you.
runeveryday — 2011-07-03T20:59:57-04:00 — #8
anyone knows? am i right?
paul_wilkins — 2011-07-03T21:14:38-04:00 — #9
That seems to be right.