使用$ this代替$(this)可以提供性能提升吗?

Jar*_*ish 17 javascript jquery caching this

假设我有以下示例:

例一

$('.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');
}
Run Code Online (Sandbox Code Playgroud)

现在,它可能是:

例二

$('.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');
}
Run Code Online (Sandbox Code Playgroud)

这一点不是实际的代码,而是使用$(this)何时使用超过一次/两次/三次或更多次.

使用示例二而不是示例一,我的表现更好(可能有解释原因或原因)?

编辑/ NOTE

我怀疑两个是更好的一个; $this当我不可避免地忘记添加$this到事件处理程序时,我有点担心的是用我的代码加工而不是无意中引入了一个可能难以诊断的错误.我应该使用var $this = $(this),还是$this = $(this)为此?

谢谢!

编辑

正如Scott在下面指出的那样,这被认为是jQuery中的缓存.

http://jquery-howto.blogspot.com/2008/12/caching-in-jquery.html

贾里德

Dav*_*ang 38

是的,绝对使用$this.

每次使用$(this)时都必须构造一个新的jQuery对象,同时$this保留相同的对象以供重用.


一个性能测试表明,$(this)显著$this.但是,由于两者都在一秒钟内执行数百万次操作,因此不太可能产生任何实际影响,但最好还是重复使用jQuery对象.当真正的性能影响出现时,选择器而不是DOM对象被重复传递给jQuery构造函数 - 例如$('p').


至于使用的var,又总是使用var声明新的变量.通过这样做,变量只能在声明它的函数中访问,并且不会与其他函数冲突.


更好的是,jQuery旨在与链接一起使用,因此尽可能利用这一点.而不是多次声明变量并调用函数:

var $this = $(this);
$this.addClass('aClass');
$this.text('Hello');
Run Code Online (Sandbox Code Playgroud)

...将函数链接在一起以使用不必要的附加变量:

$(this).addClass('aClass').text('Hello');
Run Code Online (Sandbox Code Playgroud)

  • 同时将`$ this`声明为`var $ this`,以便`$ this`包含在`each()`范围内而不是默认的全局范围内 (3认同)