This pointing in JS has always been a headache. I learned that I was dizzy at the beginning. I checked a lot of information and saw it too much. After fighting with him for so many rounds, I finally got it to 70 or 80 points. In fact, we often complicated it. Now let everyone understand this pointing easily. I will divide it into the following situations.
This pointer:
1. This refers to the object that calls the current method (function), that is, who the function is called, this refers to whom.
Let’s see two chestnuts:
oBtn.onclick = function(){ alert(this); //oBtn } oBtn[i].onclick = fn1; function fn1(){ alert(this); //oBtn }It is easy to see that the function is called when the button object is clicked, so this refers to obtn. These two cases are equivalent, but the way to write the function is called differently.
2 When nesting functions in a function, this in the nested function refers to window. Don’t go into this too deeply, because this is a feature of JS.
Let’s see a chestnut:
oBtn.onclick = function(){ alert(this); //oBtn(Remember oBtn here) fn1(); } function fn1(){ alert(this); // window }3. For the above situation, what should we do when we need this pointing button in fn1? There are two methods at this time.
1) Pass this as a parameter to the function
2) Save this and assign it to another variable
Let’s see two chestnuts:
oBtn.onclick = function(){ alert(this); //oBtn fn1(this); 1 Pass the above this as a parameter to the function} function fn1(obj){ alert(obj); // oBtn } var that = null;oBtn[i].onclick = function(){ alert(this); //oBtn that = this ;// Save this above to another variable fn1();}function fn1(){ alert(that); // Point to oBtn}OK, this is the most basic one, and many complex ones also evolved from the basic ones. Is it easy to master?
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.