Javascript function question

Posted by Raj on Stack Overflow See other posts from Stack Overflow or by Raj
Published on 2010-05-21T07:41:59Z Indexed on 2010/05/21 7:50 UTC
Read the original article Hit count: 231

Filed under:

I searched but couldn't find an answer to this seemingly easy question, so...

Suppose I have a loop in which I need to set callbacks. My callback function looks like this:

function callback(var1) { // code }

Now my loop is something like this:

for( //condition)
{
  var x = something_different_each_time;
  document.getElementById('foo').addEventListener('click', function() { callback(x); }, false);
}

Now it looks like even if the loop runs n times, the anonymous function is compiled only once -- and hence every invocation of callback is called with the same argument (even though x varies in the loop every time).

I must be missing something here.. any help is greatly appreciated! :)

© Stack Overflow or respective owner

Related posts about JavaScript