You can check this with HTML: https://jsfiddle.net/vdrr4519/ .
Items
'multifunc' is introduced with an example with many singlefunc functions - with one. See, We take all the elements with the class and pass their functions.
multifunc(document.querySelectorAll('.multifunc'));
The function starts the 'for' loop and adds a 'click' event listener. Therefore, the element must warn its index when pressed (starting at 0). But in the example with many functions, the wrong value is created (due to closure, other answers also indicate a problem).
I think I should also say that it does not release functions with one function / mutliple - this is a matter of working with closure. You see, I can implement a working example with many closures: https://jsfiddle.net/pr7gqtdr/1/ . I do basically the same thing as in the handler with one function, but each time I call the new function "helper":
nodes[i].onclick = function (i) { return function (e) { alert(i); }; }(i);
See, this (i) at the end is an immediate function call, so onclick gets the function with the variable i set in the close.
But, the options of one function are slightly better, because, in my opinion, this is more efficient memory. Functions are objects. If you create many of them, you take more memory in general. Therefore, choosing from them, I stick to the option function "handler".
everyonesdesign
source share