What's a Closure?

  1. What's a Closure?
  2. Variables and Values
  3. Defining Functions
  4. Side Effects
  5. Functions are Values
  6. Returning Functions
  7. Function Scope
  8. Nested Functions
  9. Stateful Closures
  10. Private Data
  11. Asynchronous Callbacks
  12. Continuation Passing

Private Data

Once the outer function is done it doesn't have access to the outer scope any more. Every time you invoke the outer function a new closure will be created with a distinct binding for the outer scope. This leads to the conclusion that the closed over values are entirely private and hidden away from anyone except the inner function.

This means we can use closures to provide some protection for hidden state. In the makeCounter example, the only code that could update the count variable was the inner function. If you create multiple counters, they each have a private count that is inaccessible to anyone else.

Here's an example that shows how to create a single variable that is private.

This is similar to the last example with makeCounter, but here there is just one counter. Notice the () at the end of the definition of counter. Also, the invocation has been wrapped in parentheses to make it easier to see (required by JSLint).

Define a function named accumulator that takes one argument and returns a running total of all the arguments it has seen.


about news main