Memory overhead of anonymous functions and named functions when used as jquery callbacks

I learn about JS / JQuery and anonymous functions and closures. I saw such examples:

$('.button').click(function(){ /* Animations */ /* Other Stuff */ }); 

If there is more than one button, is it inefficient? Isn't it just storing such copies of an anonymous function prototype in memory? (correct my terminology) Isn't it better to do this:

 function handleClick(){ /* Animations */ /* Other Stuff */ } ('.button').click(handleClick); 

Or even this if a link to the button is required:

 function handleClick($obj){ /* Animations */ /* Other Stuff */ } //multiple anon functions again, but they all reference ONE handleClick function ('.button').click((function($obj){ return function(){handleClick($obj)}; })($(this)); 
+6
source share
2 answers

By design, the observer pattern stores only one instance of the observer. Then the event handler calls this observer several times with other instances of the event object that contains the event parameters: which element triggered the event, what is the context, etc.

Thus, the handler is not duplicated, but is mentioned in each "listener store".

Note:
Kemal Dag also notes that anonymous functions, by definition, offer less performance than a named function, I do not know if this is true, but if so, the difference is not significant. Especially for a language like JavaScript, which uses anonymous functions so widely, it cannot afford to affect performance.

+2
source

When you use named functions, it lives only with global closure, but if you define functions at runtime, they are created inside (closing the parent function) of the new closure, as a result of which the parent variables are saved after, even if you do not need this function anymore .

In the short term, try anonymous functions only if you need to access the variables located in the parent function. Anonymous functions are almost always more expensive than named functions. But named functions defined in global closure pollute the global namespace, they decide.

+3
source

Source: https://habr.com/ru/post/953310/


All Articles