Noel
Noel

Reputation: 51

Is there any difference between (this) and (_this) in jquery?

What is the difference between these 2 statements

$(this) and $(_this) in jquery.

Upvotes: 0

Views: 4290

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

$(this) is the current element selector of the context but $(_this) is a normal variable selector.

For eg:

$('p').on('click',function(){
  var _this = $('div').eq(0);
  console.log($(_this));//first div
  console.log($(this));//clicked element 'p'
});

But usually this type of variable is used like this:

$('p').on('click',function(){
  var _this = $(this)//clicked element 'p'
  setTimeout(function(){
   //$(this) won't refer to clicked element 'p' because it's out of context
   //$(_this) will refer to clicked element
  });
});

Upvotes: 1

Related Questions