是否需要缓存jQuery $(this)

diz*_*ers 4 variables jquery caching variable-caching

我最近发表了一篇关于jQuery性能的博客文章(即http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/),并在所有这些我们都应该将jQuery对象缓存到javascript变量.

但是,我需要知道的是,这是否适用于$(this).如果我这样做,我会获得性能:

$("#some-link").click("click", function(){
  var $this = $(this);
  $this.doSomeThing();
});
Run Code Online (Sandbox Code Playgroud)

预先感谢您的帮助.

mau*_*ris 7

this 可以指许多不同的对象.

缓存$(this)可能并不重要,因为this它已经是当前元素,因此jQuery不需要在DOM中搜索此元素.

但是,如果您有多次调用$(this),在单个函数中,最好放入$(this)变量而不是$(this)多次调用.

$("#some-link").click("click", function(){
  var $this = $(this);
  $this.doSomeThing();
  $this.doThisThing();
  $this.doThatThing();
});
Run Code Online (Sandbox Code Playgroud)

会更有效率

$("#some-link").click("click", function(){
  $(this).doSomeThing();
  $(this).doThisThing();
  $(this).doThatThing();
});
Run Code Online (Sandbox Code Playgroud)