HTML and CSS Reference
In-Depth Information
fore, when we invoke the function that was returned from f2 , there would be no i variable
for it to access (since it has been destroyed). This is not the case:
> incrementer()
1
> incrementer()
2
> incrementer()
3
When the anonymous function was defined inside function f2 it “closed” over its environ-
ment as it existed at that point of time, and kept a copy of that environment. Since the vari-
able i was accessible when the function was declared, it is still available when the function
is invoked. JavaScript has realised that the anonymous function refers to the variable i , and
that this function has not been destroyed, and therefore it has not destroyed the i variable it
depends on.
If we construct another function using the same mechanism:
> incrementer2 = f2()
This will also have access to a variable called i as it existed when the function was created,
but it will be a new version of that variable:
> incrementer2()
1
> incrementer2()
2
> incrementer2()
Search WWH ::




Custom Search