A
Are Nybakk
Hi, I've stumbled into a problem I just can't figure out. I found out
that variables in JS don't have local scope inside brackets in say, a
loop, but things still doesn't add up. Also, the phenomena seemed very
much alike to a closure-related one, but I'm not returning any
functions as far as I can see (I'm fresh when it comes to closures
tho). Let me illustrate the very basic task at hand, which is filling
an array with new objects. All seven positions in the array returned
point to the same object!
---code---
var o = new Array();
for(var j=0; j<7; j++) {
//Create object
var obj = new SomeType();
//Manipulate object
obj.doSomething();
o[j] = obj;
}
//Array not what is expected here
someOtherObj.setArray(o);
---/code---
I also tried the code below to no avail. I don't see how it's any
different.
---code---
var o = new Array();
for(var j=0; j<7; j++) {
//Create object
o[j] = new SomeType();
//Manipulate object
o[j].doSomething();
}
//Array not what is expected here
someOtherObj.setArray(o);
---/code---
Does anyone have any enlightening explanations for why this occurs,
and what a solution might be?
Thanks
that variables in JS don't have local scope inside brackets in say, a
loop, but things still doesn't add up. Also, the phenomena seemed very
much alike to a closure-related one, but I'm not returning any
functions as far as I can see (I'm fresh when it comes to closures
tho). Let me illustrate the very basic task at hand, which is filling
an array with new objects. All seven positions in the array returned
point to the same object!
---code---
var o = new Array();
for(var j=0; j<7; j++) {
//Create object
var obj = new SomeType();
//Manipulate object
obj.doSomething();
o[j] = obj;
}
//Array not what is expected here
someOtherObj.setArray(o);
---/code---
I also tried the code below to no avail. I don't see how it's any
different.
---code---
var o = new Array();
for(var j=0; j<7; j++) {
//Create object
o[j] = new SomeType();
//Manipulate object
o[j].doSomething();
}
//Array not what is expected here
someOtherObj.setArray(o);
---/code---
Does anyone have any enlightening explanations for why this occurs,
and what a solution might be?
Thanks