Wednesday, June 11, 2008

Javascript Closure

I think most people writing a lot of javascript eventually run into a misunderstanding about closures. Take a look at the code below. The code dynamically creates three buttons that show an alert box when clicked upon. What do you think will happen when you click each button?

The problem is that the animal variable used in the button's onclick event is changed in the loop and thus the event will use the value that was last assigned to the variable. In order to get the onclick event to use the value of the variable at the time the onclick is defined you will need to define an execution context which will capture this value. This can be done using a function. While this can be done with a regular function here is a nifty little example of doing this with an anonymous function:

Here is a slightly different (possibly simpler) way to create the function closure: