Because you are creating multiple Function
objects instead of reusing only one.
An example of creating an identical function ...
for (var i = 0; i < 10; i++) { // v--creating identical function in each iteration. (function(j) { var el = document.createElement('a'); el.onclick = function() { alert(j); }; document.body.appendChild(el); })(i); }
An example of reusing a named function ...
for (var i = 0; i < 10; i++) { var el = document.createElement('a');
Two examples have the same result, but the second does not require the overhead of performing two functions during the cycle. Instead, it creates only one handler.
user1106925
source share