Looking behind the curtain...
Let’s step through the code to see how the counter works.
We call makeCounter, which creates a counter function and returns it along with an environment containing the free variable, count. In other words, it creates a closure. The function returned from makeCounter is stored in doCount.
We call the function doCount. This executes the body of the counter function.
When we encounter the variable count, we look it up in the environment, and retrieve its value. We increment count, save th...
- 11. Anonymous Functions, Scope and Closures: Serious functions
- Publisher: O'Reilly Media, Inc.
- Released: March 2014
How does the closure work via returning a function from a function?