Talk about the direction of this in JS

  • 2021-06-28 11:19:14
  • OfStack

this pointing to 1 in JS has always been a headache. I thought at first I studied dark and dim, checked a lot of data, looked at a lot of data, fought with him so many rounds, and finally got it to 78 points. In fact, it is often complicated for us. Now we can easily understand this's pointing. I will divide it into the following situations.
this direction:
1. this refers to the object that calls the current method (function), that is, who the function is called from and who this refers to.
Come and see two chestnuts:


 oBtn.onclick = function(){ 
    alert(this);  //oBtn
 }

 

 oBtn[i].onclick = fn1;

  function fn1(){ 

  alert(this); //oBtn
 } 

It is easy to see that a function is called when a button object is clicked, so this refers to obtn, which is the same, except that the function is called in a different way.
2 When a function is nested inside a function, this in the nested function refers to window. Do not go into this reason too deeply, because it is a feature of JS.
Chestnuts:


oBtn.onclick = function(){

   alert(this); //oBtn( Remember here or oBtn)

   fn1(); 
  }

 function fn1(){ 
  alert(this); // window
  } 

3. There are two ways to do this when we need the this pointing button in fn1.
1) Transfer this as a parameter function
2) Save this and assign it to another variable
Come and see two chestnuts:


oBtn.onclick = function(){

   alert(this); //oBtn

   fn1(this); 1  Put the above this Pass function as parameter 
  }

 function fn1(obj){ 
  alert(obj); // oBtn
 }


var that = null;
oBtn[i].onclick = function(){

  alert(this); //oBtn
  that = this ;//  Put the above this Save and assign to another 1 Variables 
  fn1();
}

function fn1(){ 
  alert(that); //  point oBtn
} 

OK, the direction of this, is the most basic of these, many complex are also evolved from the basic.Is it easy to master?


Related articles: