wood burning stoves 2.0*
The moose likes HTML, CSS and JavaScript and the fly likes Scope Chain / Closures Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Scope Chain / Closures" Watch "Scope Chain / Closures" New topic
Author

Scope Chain / Closures

Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

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 ]

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
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

Joined: Dec 11, 2004
Posts: 13410

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Scope Chain / Closures
 
Similar Threads
How to submit the form using hyperlink
How to bring window in focus that is already open
Using Hyperlink instead of Button
can we pass parameters in anchor tag like using post method
problem with submit button