I’ve been doing this:
$('#id').on('click',function(e){myFunction(var1,var2);});
function myFunction(x,y){blah blah blah}
I’m wanting to change to this:
$('#id').on('click',function(e){blah blah blah});
If I do this with lots of different DOM elements, am I consuming more memory space because I’m multiplying the space taken up by myFunction with each closure? Or does it just use a pointer?
The first code has the advantage of reuse, but has the disadvantage of defining an anonymous function just to call the real function. If it really matters, then the extra function is an overhead.
The second one will take much less memory since you are passing only one function. Functions are also passed by reference. Meaning this function could be stored once and called by many different callers.
However, the way you attach it also affects performance. If you do it like this:
this one calls jQuery 4 times (2
$()and 2on()), creates 2 anonymous functions and calls an external function twice. count: 6 calls, 3 functions just to execute your operation (not including internal jQuery calls).if you do it this way, the function isn’t reusable anymore but you got 4 calls to jQuery, 2 functions but you are repeating the code. not good from a DRY perspective.
this one, you have 2 calls, and 1 function. this one is better.
you could also do it this way, the function is reusable with a sacrifice of an additional anonymous function and call. count: 3 calls, 2 functions.
You could harness the power of
.onby attaching the handler to the “nearest common parent”, nearest so that the bubble won’t travel up very far. in comparison,live()attaches events to thedocument, making handlers available even to new elements. But attaching to thedocumentmakes it very far for deeply nested elements.