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).
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).