Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scope Chain / Closures

 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Eric Pascarello
author
Rancher
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The closure is working exactly the way it is supposed to. The variable "i" gets substituted only when the function is called, not when you assign it.

3 ways of doing it in the order I would do it

1) Set a property and reference it like you are doing since it is setting the property with the current value.


2) Create an anonymous function with one parameter called 'x' and this function is called directly setting the value you wanted.

3) Creating a function by building a string with the current value. Downside is it is slow.


Eric
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Eric.
I agree, the first option looks the cleanest.

The syntax for your second choice is interesting.
I haven't seen a function created and called from the same statement like that before.

I appreciate it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic