This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The following code draws 10 buttons to the screen:
Clicking on any of the buttons displays an alert with "10" in it. I understand that I'm working with a closure and that the variable "i" is part of the lexical environment in which the anonymous function registered to each button's onclick event was created.
I would have thought that each button's function would retain the current value of "i" when the function was created but this is not the case.
Also, if I create local variable in the anonymous function and assign it the value of "i", the result is still "10" when each button is clicked:
Two questions: What am I missing? and.. What is the proper way to insure each function has a copy of what "i" was when the function was created?
I was able to achieve this by adding a property to the button object and then retrieving it using"this.propert"
but this doesn't seem like the right approach. [ April 20, 2007: Message edited by: Ben Souther ]