Google isn't helping me figure this one out. Is there any reason not to do the following:
var test = $('something');
$(test).stuff();
Instead of the doing it this way:
var test = $('something');
test.stuff();
Basically I find the code much easier to read when it's in the jQuery selector format, even though it doesn't need to be.
Both methods appear to work the same.
Thanks!
The first one can be significantly slower, depending on the size of the object. If you only use it a couple times it won't make that much a difference, but if you use it a lot maybe you could use this popular naming scheme:
If a variable contains a jQuery object prepend the variable name with $
. Name everything else normally, and don't name any variables that do not contain jQuery objects with a $. So you would write:
var $test = $('something');
$test.stuff();
Which makes it clear that test is a jQuery object if you've been following the same naming convention.
This is from the jQuery Docs:
Cloning jQuery Objects
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
So the difference is that jQuery is making a clone of the jQuery object being passed to the $() function (which creates a small amount of extra overhead).
Link: http://api.jquery.com/jQuery/
test.stuff()
is faster.
Here's some benchmarking evidence: http://jsperf.com/selector-variation-test
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