473,404 Members | 2,187 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

closure problem

for ( var i = 0; i < div.firstChild.childNodes.length; ++i )
{
var marker = new Object();
marker.iii = i;

sys.addListener( marker, "click", function()
{
alert(marker.iii);
});
}

looks like when clicked - marker object has the value of the last
object thru the loop.

i'd like it to display the appropriate iii value.
Mar 6 '08 #1
2 1396
On Mar 6, 8:54 am, jman <erjdri...@gmail.comwrote:
for ( var i = 0; i < div.firstChild.childNodes.length; ++i )
{
var marker = new Object();
marker.iii = i;

sys.addListener( marker, "click", function()
{
alert(marker.iii);
});
}

looks like when clicked - marker object has the value of the last
object thru the loop.

i'd like it to display the appropriate iii value.
JavaScript has function level scoping as opposed to block level (like
other languages). Your marker object is visible across iterations and
the closure will always reference the last instance of the marker
object. I believe you could stop this from happening using a self-
executing anonymous function, like so:

for ( var i = 0; i < div.firstChild.childNodes.length; ++i )
{
(function() {
var marker = new Object();
marker.iii = i;

sys.addListener( marker, "click", function()
{
alert(marker.iii);
});
})(); /* These brackets are necessary to execute the anonymous
function */
}

This should scope the marker inside the anonymous function and the
closure should behave the way you want.
Mar 6 '08 #2


Nick Fletcher wrote/zu Deiner Priorität-Alpha-1-Nachricht von Sternzeit
06.03.2008 18:16:
On Mar 6, 8:54 am, jman <erjdri...@gmail.comwrote:
> for ( var i = 0; i < div.firstChild.childNodes.length; ++i )
{
var marker = new Object();
marker.iii = i;

sys.addListener( marker, "click", function()
{
alert(marker.iii);
});
}

looks like when clicked - marker object has the value of the last
object thru the loop.

i'd like it to display the appropriate iii value.

JavaScript has function level scoping as opposed to block level (like
other languages).
JFYI: Since version 1.7 it also has block scoping, but you need to declare
that version as it introduces new keywords.

http://developer.mozilla.org/en/docs...scope_with_let
Your marker object is visible across iterations and
the closure will always reference the last instance of the marker
object. I believe you could stop this from happening using a self-
executing anonymous function, like so:

for ( var i = 0; i < div.firstChild.childNodes.length; ++i )
{
(function() {
var marker = new Object();
marker.iii = i;

sys.addListener( marker, "click", function()
{
alert(marker.iii);
});
})(); /* These brackets are necessary to execute the anonymous
function */
}

This should scope the marker inside the anonymous function and the
closure should behave the way you want.
You create an additional closure of `i' needlessly. It is overkill
and the base code is still very inefficient and error-prone.

Consider this instead:

for (var i = 0, len = div.firstChild.childNodes.length; i < len; ++i)
{
var marker = new Object();
marker.iii = i;

sys.addListener(
marker, "click",
(function(me) {
return function() {
window.alert(me.iii);
};
})(marker)
);
}
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
Mar 7 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
by: Ted Lilley | last post by:
What I want to do is pre-load functions with arguments by iterating through a list like so: >>>class myclass: .... pass >>>def func(self, arg): .... print arg >>>mylist = >>>for item...
1
by: Victor Ng | last post by:
Is there a way to preserve the argspec of a function after wrapping it in a closure? I'm looking for a general way to say "wrap function F in a closure", such that inspect.getargspec on the...
9
by: Mikito Harakiri | last post by:
Transitive closure (TC) of a graph is with TransClosedEdges (tail, head) as ( select tail, head from Edges union all select e.tail, ee.head from Edges e, TransClosedEdges ee where e.head =...
7
by: Csaba Gabor | last post by:
I feel like it's the twilight zone here as several seemingly trivial questions are bugging me. The first of the following three lines is a syntax error, while the last one is the only one that...
9
by: User1014 | last post by:
I'm a javascript noob and have a question concerning some code I've come across that I'm trying to understand. Here is a snippet of the relevant section: (snip) var closure = this; var xhr =...
0
by: Gerard Brunick | last post by:
Consider: ### Function closure example def outer(s): .... def inner(): .... print s .... return inner .... 5
11
by: Huayang Xia | last post by:
What will the following piece of code print? (10 or 15) def testClosure(maxIndex) : def closureTest(): return maxIndex maxIndex += 5 return closureTest()
4
by: LAN MIND | last post by:
?
4
by: JavascriptProgrammer | last post by:
In the following code: ----------------------- function get() { return function() { alert(x); } }; function foo(s) { var x = s; this.getX = get();
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.