JQuery "$ (this)": is reuse effective?

Is using $ (this) repeatedly efficient or is it better to store it in a variable? I saw how it was repeatedly used in a lot of jQuery code, but since this is a constructor call, I think it should be unnecessarily slow, am I mistaken?

+4
source share
3 answers

Just for fun - a dimension. To see the difference, you will need to call $(this)tens of thousands of times (depending on the processor).

The difference in 100,000 calls is approximately equal to 100vs. 70milliseconds $(this), which is slower.

var testCount = 100000;

$('div').each(function(){
  var self = $(this);
  
  // Measurement using $(this) selector
  var t1 = new Date();
  for (var i = 1; i <= testCount; i++){
  	var nil = $(this).attr('id');
  }
  console.log('T1', (new Date()) - t1);
  
  // Measurement using saved declaration
  var t2 = new Date();
  for (var i = 1; i <= testCount; i++){
  	var nil = self.attr('id');
  }
  console.log('T2', (new Date()) - t2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">  
</div>
Run codeHide result

var self = $(this), , - - ( ).

+1

$(this) DOM, this, jQuery. , , . , , varibale, .

$() - jQuery, , $(this), , . jQuery:

jQuery = function(selector, context) {
    return new jQuery.fn.init(selector, context);
};

, new. , jQuery , this DOM .

, script, , $('.my-element'). , jQuery .

, $(this) . / . , !

+2

$(this), 10 , -

$('.my-elem').on('click', function() {
    var $this = $(this);
    $this.doSomething();
});

: ! :

var $this = $(this);

$('.my-elem').on('click', function() {
    $this.doSomething(); 
});

$('.other-elem').on('click', function() {
    $this.doSomething();
});

. , , , ... .

+1

Source: https://habr.com/ru/post/1651786/


All Articles