Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason not to use $(test).stuff(); vs test.stuff(); given that test = $('something');?

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!

like image 732
Ryan Ewen Avatar asked Jul 29 '11 20:07

Ryan Ewen


3 Answers

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.

like image 68
Paul Avatar answered Nov 08 '22 02:11

Paul


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/

like image 21
Jasper Avatar answered Nov 08 '22 00:11

Jasper


test.stuff() is faster.

Here's some benchmarking evidence: http://jsperf.com/selector-variation-test

like image 5
AlienWebguy Avatar answered Nov 08 '22 01:11

AlienWebguy