【发布时间】:2011-08-09 03:00:48
【问题描述】:
假设我有以下示例:
示例一
$('.my_Selector_Selected_More_Than_One_Element').each(function() {
$(this).stuff();
$(this).moreStuff();
$(this).otherStuff();
$(this).herStuff();
$(this).myStuff();
$(this).theirStuff();
$(this).children().each(function(){
howMuchStuff();
});
$(this).tooMuchStuff();
// Plus just some regular stuff
$(this).css('display','none');
$(this).css('font-weight','bold');
$(this).has('.hisBabiesStuff').css('color','light blue');
$(this).has('.herBabiesStuff').css('color','pink');
}
现在,可能是:
示例二
$('.my_Selector_Selected_More_Than_One_Element').each(function() {
$this = $(this);
$this.stuff();
$this.moreStuff();
$this.otherStuff();
$this.herStuff();
$this.myStuff();
$this.theirStuff();
$this.children().each(function(){
howMuchStuff();
});
$this.tooMuchStuff();
// Plus just some regular stuff
$this.css('display','none');
$this.css('font-weight','bold');
$this.has('.hisBabiesStuff').css('color','light blue');
$this.has('.herBabiesStuff').css('color','pink');
}
重点不是实际的代码,而是$(this)在使用超过一次/两次/三次或更多时的使用。
我使用示例二是否比示例一在性能方面更好(可能会解释为什么或为什么不)?
编辑/注释
我怀疑两个更好一个;我有点害怕的是在我的代码中添加$this,而不是在我不可避免地忘记将$this 添加到事件处理程序时无意中引入了一个潜在的难以诊断的错误。那么我应该使用var $this = $(this) 还是$this = $(this) 呢?
谢谢!
编辑
正如 Scott 在下面指出的,这在 jQuery 中被视为缓存。
http://jquery-howto.blogspot.com/2008/12/caching-in-jquery.html
贾里德
【问题讨论】:
-
关于那个答案here(现在已删除):我想破解那个服务器:p
标签: javascript jquery caching this