Strange Scoping Problem


S

shaneal

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 = 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.javascript).
 
Ad

Advertisements

D

David Mark

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 = 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?


Because i *is* 5 after the loop is finished. All of the functions
created are referencing the same i variable. If the for loop is run
in the global context, then i is a global variable. If not, i is a
local variable and part of a closure formed by assigning references to
the functions to the global functions array.

Something like this will produce the desired results:

functions = (function(j) { return function() { printNum(j); }; })
(i);

That pattern creates a distinct closure for each of the five
functions.
I was banging my head on a strange problem for a bit, until I finally

Scope-related issues (particularly closures) are a common source of
confusion for beginning JS programmers.

[snip]
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top