Besides storing the attributes of a DOM object in a loop, you can also use function locks to “freeze” a copy of variables in a loop for a particular function call. You can do it as follows:
for (var a=index; a<rows.length; a++) { tr = rows[a]; tr.onclick = function(tr, a) { return(function() { DropDownManager.onItemClick(tr, a); }); }(tr,a); }
This means that it assigns tr.onclick the results of an anonymous function call, which takes two variables as parameters (named tr and a) and passes the current values of tr and a as parameters (this transmission, the current values “freeze” the current values of these variables inside this function.
The result of this function call is another anonymous function. Since this internal anonymous function is now assigned to tr.onclick, it creates a function closure that retains all the state that is currently in this closure. This state includes the “frozen” values of tr and a, but they remain internal only to close this function, so every time a new function closure is created through the loop with a new “frozen” and “saved” value of tr and a.
jfriend00
source share