Noel Noel - 4 months ago 12
Javascript Question

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

What is the difference between these 2 statements

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

Answer

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