Does jQuery $(this) need to be cached

后端 未结 6 696
一生所求
一生所求 2021-01-13 14:05

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-performanc

6条回答
  •  佛祖请我去吃肉
    2021-01-13 14:42

    this may refer to many different objects.

    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.

    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();
    });
    

    would be more efficient than

    $("#some-link").click("click", function(){
      $(this).doSomeThing();
      $(this).doThisThing();
      $(this).doThatThing();
    });
    

提交回复
热议问题