Resources for closure
Q: What is closure
- When you declare a local variable, that variable has a scope. Generally local variables exist only within the block or function in which you declare them.
- If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.
When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.
This is how we normally expect things to work. A closure is a persistent local variable scope
The scope object, and all its local variables, are tied to the function, and will persist as long as that function persists.
This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.
Here I have defined a function within a function. The inner function gains access to all the outer function’s local variables, including
a. The variable
a is in scope for the inner function.
Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable
fnc, so that it persists after
outer has exited, all of the variables that were in scope when
inner was defined also persist. The variable
a has been closed over – it is within a closure.
Note that the variable
a is totally private to
As you might be able to guess, when I call
fnc() it prints the value of
a, which is “1”.
In a language without closure, the variable
a would have been garbage collected and thrown away when the function
outer exited. Calling fnc would have thrown an error because
a no longer exists.
a persists because variable scope is created when the function is first declared, and persists for as long as the function continues to exist.
a belongs to the scope of
outer. The scope of
inner has a parent pointer to the scope of
fnc is a variable which points to
a persists as long as
a is within the closure.
Q: How to retain access to a functions after the function call that creates them return?
- passing it to setTimeout()
- returning that function from the called one
- saving that function to a global var