Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory overhead of anonymous functions vs named functions when used as Jquery callbacks

I'm learning about JS/JQuery and anonymous functions and closures. I've seen examples like this:

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

If there is more than one button, isn't that inefficient? Isn't that just storing similar copies of an anonymous function's 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 reference to the button is needed:

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));
like image 764
Alex Avatar asked Sep 06 '13 11:09

Alex


1 Answers

When you use named functions, it only lives on a global closure, but if you define functions on runtime, they are created within (parent function's closure) a new closure, resulting in parent variables being preserved after, even if you do not need that function anymore.

In short terms, try anonymous functions only if you need to access variables located in parent function. Anonymous functions are nearly always more expensive then named functions. But named functions defined in global closure, pollutes global namespace, decide for yourself.

like image 120
Kemal Dağ Avatar answered Oct 01 '22 23:10

Kemal Dağ