473,750 Members | 2,533 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Strange Scoping Problem

Hello all,

I've been trying to learn some javascript and I ran into a strange
scoping problem I was hoping someone here could help with. I have a
fair amount of experience with functional programming, but very little
with javascript, so please excuse the unidiomatic code.

When I do:

var functions = new Array();

function printNum(x) {
alert(x);
}

for(var i=0;i<5;i++) {
functions[i] = function() { printNum(i);}
}

Now, I'd not expect
functions[0]();
to alert with 0, but instead it alerts with 5. Why is that, and how
can I work around it?

I was banging my head on a strange problem for a bit, until I finally
managed to track down the problem to something isomorphic to this bit
of code.

PS: functions[1-4](); all alert with 5 too ... in case that is
relevant

Thanks for the help, and I apologize in advance for any breaches of
protocol I've made here (first time on comp.lang.javas cript).
Feb 17 '08 #1
1 1578
ah, many thanks. your explanations make perfect sense.
Feb 17 '08 #2

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

Similar topics

2
1651
by: David Stockwell | last post by:
Hi, Another of my crazy questions. I'm just in the process of learning so bear with me if you can. I actually ran it.... with two test cases TEST CASE 1: Say I have the following defined: --- beginning of code snippet ---- def me(aFile):
3
1412
by: Johan | last post by:
I don't get it: I'm trying to write a "readfile" function which would replace some code from a __init__ function: 1 import string 2 class landdict: 3 def __init__(self, file): 4 # Laadt de dictionnary van landen. 5 # Kijk in de actiefspel-file voor de file van waaruit je moet laden.
5
1903
by: Gunnar G | last post by:
Is there a problem with the declaration of the y-variable in the for loop? I'm not sure about the break, (if it should be there or not since I didn't write the original code), but the error: "initialization of y is skipped by case label" was reported. int main(){ int x; int a=4; switch (a){ case 1: for (int y=0;y<10;y++) x=y; break;
1
2154
by: Michael | last post by:
I am having a problem with scoping of parameters in my XSLT Stylesheet...here is the stylesheet (the xml document is irrelevant for the example) <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:param name="myParam">Stylesheet Default</xsl:param> <xsl:template match="/"> <result_explicit_call>
4
3511
by: Joel Gordon | last post by:
Hi, When I try and compile the a class containing the following method : public void doSomething() { for (int i=0; i<5; i++) { IList list = new ArrayList(); Console.WriteLine( i / (list.Count) ); } int i = 23;
5
1692
by: cody | last post by:
I have a very funny/strange effect here. if I let the delegate do "return prop.GetGetMethod().Invoke(info.AudioHeader, null);" then I get wrong results, that is, a wrong method is called and I have no clue why. But if I store the MethodInfo in a local variable I works as expected. I do not understand why this is so, shouldn't both ways be semantically equal?
9
1930
by: NevilleDNZ | last post by:
Can anyone explain why "begin B: 123" prints, but 456 doesn't? $ /usr/bin/python2.3 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13, in ? A() File "x1x2.py", line 11, in A
3
2071
by: morris.slutsky | last post by:
So every now and then I like to mess around with hobby projects - I often end up trying to write an OpenGL video game. My last attempt aborted due to the difficulty of automating game elements and creating a good level editor - I basically needed a scripting language to control the C modules of the game and, after a half-assed attempt or two to make my own, I just gave up. So naturally this seems like a job for Python. Embedding Python...
17
2900
by: Chad | last post by:
The following question stems from Static vs Dynamic scoping article in wikipedia. http://en.wikipedia.org/wiki/Scope_(programming)#Static_versus_dynamic_scoping Using this sites example, if I go like this: #include <stdio.h> int x = 0;
0
9001
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9398
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8265
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6811
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4716
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4894
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2227
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.