I\'m trying to understand closures and am looking at the W3Schools javascript tutorial. This is one example they give by making a counter.
The concept of closures could be explained as having functions and their contexts. A context is somewhat a kind of storage attached to the function to resolve variables captured (thus named closure?).
When the example code is executed:
var add = (function () {
var counter = 0; // This is promoted to the below's function context
return function () {return counter += 1;}
})();
You create a context where the counter
variable is promoted to the anonymous function context thus you can access that variable from the current scope.
This diagram more or less explains it:
In this case, X and Y are captured by the function context and that is carried over all the executions of that function.
Now, this is just the V8 implementation of lexical environments.
See Vyacheslav Egorov great explanation on closure implementations using V8: Grokking V8 closures for fun (and profit?)