JavaScript is a pretty good language to illustrate closures, if you use functions and declare all of your variables at the beginning of each function. :)
In the demo below, the closure we're interested in is the combination of the code inside "munger scope", and the environment it resides in. To do its job, munger must search its lexical environment to find each variable. The lexical environment is illustrated by the boxes. Searching for "foo", it must first check munger scope (local), beta scope, alpha scope, and then finally succeeds with the global scope.
In the code at the bottom, the demo1 and demo2 invocations don't influence each other. That combination of code+environment providing independent values is a closure.
Ahhh, I see, so not only does the closure scoop up the value of variables at 'define-time', but each closure keeps track of the state of its variables (its 'free variables?') so that their values may increment over time rather than reset.
Thanks for you (rather cool) illustration. I tested the code and it also worked :)
In the demo below, the closure we're interested in is the combination of the code inside "munger scope", and the environment it resides in. To do its job, munger must search its lexical environment to find each variable. The lexical environment is illustrated by the boxes. Searching for "foo", it must first check munger scope (local), beta scope, alpha scope, and then finally succeeds with the global scope.
In the code at the bottom, the demo1 and demo2 invocations don't influence each other. That combination of code+environment providing independent values is a closure.