Page 4: Closure Example
On this page, we’ll try a more realistic example of a closure to create “interesting” behavior for handler functions. We’ll use buttons since they are easy.
A Counter
Let’s make a program that has buttons that count up. Every time we press the button, it increments the counter.
We don’t know how many of these buttons we will need.
Here’s a simple example with 1 button. It’s in F-04-01.html and F-04-01.js. It’s pretty simple, it uses a global variable to keep count.
Now, let’s do that for 5 buttons. Here’s one with a solution. F-04-02.html has the 5 buttons, but F-04-02.js is empty so you can try it yourself. If you want to try it before seeing my solution.
OK, here’s my solution.
It works. You can look at the code in F-04-03.js. If you understand closures, its a trivial extension of the first program.
You can read the code to see how it works.
Closures
This should give you enough of a sense of what closures are and how they work to get started with them.
They do take a bit of practice, in particular, to realize when they might be useful, and how to best apply them to a problem.
Actually, I will give you one more simple example on the next page.
Next: Another Closure Example