Is it always best practice to use:
var $this = $(this);
Or is $(this) cached and therefore the above line is just for saving two characters?
Is it always best practice to use:
var $this = $(this);
Or is $(this) cached and therefore the above line is just for saving two characters?
Using $(this)
calls at least two (and possibly more than two) functions and allocates an object each and every time you use it (consuming memory that eventually has to be reclaimed). That's all extra work if you're just going to reuse the same thing. I'd recommend calling it once and then caching the result (e.g., within the function) rather than having a dozen lines of $(this).foo();
$(this).bar();
.
$
is an alias for the jQuery
function, which looks like this:
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
}
As you can see, it creates an object, calling the constructor function jQuery.fn.init
. That function then has to figure out what it's doing, because, jQuery uses the jQuery
function for 18 different things. I'm not saying it doesn't do it quickly, but why do all that extra work. :-)
Edit: In the case where you're passing a DOM element into it (which is usually what $(this)
is doing), jQuery.fn.init
doesn't make any further function calls. So "just" two plus the allocation.
The $ function will make a new instance of the jQuery object (or check all the existing ones, i'm not sure how unique id works now), but it can be a huge overhead in a loop/each function.
So in these cases the answer is yes, in other cases it may be insignificant.
And no, it's definitely not just about characters.