最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

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!

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!

Share Improve this question edited Jun 11, 2012 at 1:31 Paul 142k28 gold badges282 silver badges270 bronze badges asked Jul 29, 2011 at 20:17 Ryan EwenRyan Ewen 1348 bronze badges 1
  • Thanks for the answers everyone. I didn't think of simply adding the dollar sign to the beginning of object variables. That makes it stand out enough for me :) – Ryan Ewen Commented Aug 2, 2011 at 3:03
Add a comment  | 

5 Answers 5

Reset to default 12

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

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.

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.

发布评论

评论列表(0)

  1. 暂无评论