Analysis of var that=this in JavaScript

  • 2021-07-21 07:26:09
  • OfStack

When reading other people's code, I found that there is such a sentence in the code written by others: var that = this ; What does this mean? After one inspection, I realized that this was the case.

In JavaScript, this represents the current object.

var that=this Is to copy the current this object into the that variable. What's the point of doing this?


$( ' #conten').click(function(){
//this It was clicked #conten
var that = this;
$( ' .conten').each(function(){
//this Yes .conten The current object in the loop 
//that It's still the one that was just clicked #conten
});
});

As you can see, the this object changes at any time in the program, and var that=this After that, that still points to this at that time before it is changed, so that the original object cannot be found.


Related articles: