I have this piece of code:
var items = [0,1];
for (var i = 0; i < 2; i++) {
var obj = new function() {
this.item = items[i];
}
window.setTimeout(function() { console.log(obj.item); }, 1000);
}
And the result is:
1
1
But I would have expected this:
0
1
I am a little bit puzzled. What is the best way to obtain this result?
I think this question is actually different than Javascript closure inside loops because I can already do this:
var items = [0,1];
var objs = [];
for (var i = 0; i < 2; i++) {
var obj = new function() {
this.item = items[i];
}
objs.push(obj);
window.setTimeout(function() { console.log(obj.item); }, 1000);
}
for (var i = 0; i < 2; i++)
console.log(objs[i].item);
And the result of the second loop will be:
0
1
The problem is to call the right obj from the setTimeout.