Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
63
rated 0 times [  64] [ 1]  / answers: 1 / hits: 19300  / 10 Years ago, thu, october 2, 2014, 12:00:00

Can someone explain to me why JSLint complains about Function inside the loop with this example:



  for (var i = 0; i < buttons.length; i++) {
(function(i) {
buttons[i].onclick = function(e) {
t.progressBars[t.current].update(buttons[i].getAttribute(data-value));
}
})(i);
}


But dosen't when I change it to:



function makeHandler(i)
{
return function() {
t.progressBars[t.current].update(buttons[i].getAttribute(data-value));
}
}

for (var i = 0; i < buttons.length; i++) {

buttons[i].onclick = makeHandler(i);

}


I don't quite understand as it seems that with each loop iteration new function object has to be returned, even though it happens inside of makeHandler() function. Why the second example is ok with JS linters?


More From » function

 Answers
8

Your two examples are not equivalent.



In the first, you are creating an anonymous function and calling it on every loop.



The inner function (the click event handler) is fine - you're assigning a new function - but it's the anonymous outer function that is inefficient in this context. In your second example the outer function is refactored out of the loop where is it only created once, instead of buttons.length times.


[#69270] Monday, September 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jennie

Total Points: 593
Total Questions: 102
Total Answers: 106

Location: Federated States of Micronesia
Member since Fri, Sep 16, 2022
2 Years ago
jennie questions
;