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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With