Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.
Why, when I call counter()()
, do I get no closure, but if I assign a variable to the result of counter()
, like var getClosure = counter()
, I then get a closure when calling getClosure()
?
function counter() { var _counter = 0; function increase() { return _counter++ } return increase; } // Double ()() to call the returned function always return 0, so no closure. counter()() // returns 0 counter()() // returns 0 counter()() // returns 0 counter()() // returns 0 var createClosure = counter(); createClosure() // returns 0 createClosure() // returns 1 createClosure() // returns 2 createClosure() // returns 3
When JavaScript reaches a return statement, the function will stop executing. If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
There are two main disadvantages of overusing closures: The variables declared inside a closure are not garbage collected. Too many closures can slow down your application. This is actually caused by duplication of code in the memory.
@Novellizator (and georg): This may or may not be true for other languages, but in JavaScript, all functions are closures. It's intrinsic to them, in JavaScript. There is nothing special about closures over other contexts that marks them out as distinct from functions that only close over the global context.
_counter
is the local variable within function counter()
. Every time when you call counter()
a new _counter
will be created.
But var createClosure = counter()
only called the function 1 time, that's why _counter
is not newly created every time and 'remembered' there (that's where closure happens)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With