Consider following code:
var a = [ { a: 'I' }, { a: 'II' }, { a: 'III' } ];
for( var i=0; i<a.length; i++ ){
var j = i;
var x = a[ i ];
x.bb = function(){
x.b = "-" + x.a + "-";
}
x.cc = function(){
a[ i ].c = "-" + a[ i ].a + "-";
}
x.dd = function(){
a[ j ].d = "-" + a[ j ].a + "-";
}
}
for( var i=0; i<a.length; i++ ){
a[i].bb();
a[i].cc();
a[i].dd();
}
console.log( a );
will result in (functions left out):
[ { a: 'I', c: '-I-' },
{ a: 'II', c: '-II-' },
{ a: 'III', b: '-III-', d: '-III-', c: '-III-' } ]
So only cc() does what I intended to do.
My question now is:
- What are the rules here how the variables are stored in the closure. (Obviously
i
is stored as a constant whilej
andx
are stored as reference to the local variables which are changed while the for-loop iterates. But why is that?) There was my mistake. The code did only work because the second and the firsti
where the same! - Is there a way to write
bb()
in a way that it stores a reference toa[ i ]
so that I don't have to use the index?
Thanks!