1

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.

Community
  • 1
  • 1
Mathew
  • 670
  • 1
  • 11
  • 21
  • Welcome to the JS closures! :) – margabit Aug 29 '13 at 13:58
  • See [this question](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Andrei Aug 29 '13 at 13:58
  • You are reassigning objet's item in each loop – Alex Aug 29 '13 at 13:59
  • you should use `for (var i = 0; i < items.length; i++)` instead using 2 – Rômulo Spier Aug 29 '13 at 13:59
  • No, the problem is the same as in that duplicate. Read the answers and understand the implications. And [avoid that `new function(){}` pattern!](http://stackoverflow.com/questions/10406552/is-it-right-to-think-of-a-javascript-function-expression-that-uses-the-new-key) – Bergi Aug 29 '13 at 14:32

0 Answers0