Tuesday, May 1, 2012

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!


Source: Tips4all

5 comments:

  1. 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.

    ReplyDelete
  2. 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/

    ReplyDelete
  3. test.stuff() is faster.

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

    ReplyDelete
  4. You'll take a performance hit for no good reason doing it the first way. The reason for this is that you are "re-jQueryifying" it. What I recommend is to write it like this var $test = $('something'); it is very clear that the variable is a jQuery object when you do that.

    ReplyDelete
  5. I don't believe the first method is correct, I think once you've declared a variable it's just that name. If you want similar syntax you can declare the variable as $test and be fine.

    ReplyDelete