问题描述
我最近遇到了一些有关jQuery性能的博客文章(即 http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/),他们都说我们应该将jQuery对象缓存到javascript变量中.
I recently came accross some blog posts about jQuery performance (i.e. http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/) and it was stated in all of them that we should cache the jQuery objects to javascript variables.
我需要知道的是,这是否也适用于$(this).如果这样做,我会提高性能吗?
What I need to know, though, is if this applies to $(this) as well.Am I going to gain in performance if I do this:
$("#some-link").click("click", function(){
var $this = $(this);
$this.doSomeThing();
});
预先感谢您的帮助.
推荐答案
this
可能引用了许多不同的对象.
this
may refer to many different objects.
缓存$(this)
可能并不重要,因为this
已经是当前元素,因此jQuery无需在DOM中搜索该元素.
Caching $(this)
may not be important, because this
is already the current element and thus jQuery does not need to search the DOM for this element.
但是在单个函数中,如果多次调用$(this)
,明智的做法是将$(this)
放在变量中,而不是多次调用$(this)
.
However in a single function if you have more than one times calling $(this)
, it is wise to put $(this)
to a variable instead of calling $(this)
many times.
$("#some-link").click("click", function(){
var $this = $(this);
$this.doSomeThing();
$this.doThisThing();
$this.doThatThing();
});
会比
$("#some-link").click("click", function(){
$(this).doSomeThing();
$(this).doThisThing();
$(this).doThatThing();
});
这篇关于jQuery $(this)是否需要缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!