Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: Using the current for-loop counter-value inside a function() { }?

on a website i want to do this: (simplified)

myHandlers = new Array();
for(var i = 0; i < 7; i++) {
  myHandlers.push(new Handler({
    handlerName: 'myHandler'+i, // works, e.g. ->myHandler1, 2, 3 etc.
    handlerFunc: function(bla) { /*...*/ alert(i); } // doesn't work,all return 7
  }
}

I could set the counter as another attribute of my Handler (which would copy the current value) and use it inside my function, but I guess, there is also a way to actually copy this value, no?

like image 438
Fabian Fritz Avatar asked Dec 28 '22 08:12

Fabian Fritz


1 Answers

When handlerFunc is called, the i inside the function refers to the i of the for loop. But that i does probably not have the same value any more.

Use a closure to bind the current value of i in the scope of an anonymous function:

handlerFunc: (function(i) { return function(bla) { /*...*/ alert(i); }; })(i)

Here an anonymous function (function(i) { … })(i) is used and called immediately. This function binds the value of i of the for loop to the local i. That i is then independent from the i of the for loop.

like image 129
Gumbo Avatar answered Dec 30 '22 23:12

Gumbo