Detailed explanation of this pointing problem in JavaScript

  • 2021-10-25 06:04:01
  • OfStack

Inscription

this in JS points to 1 straight, which is a headache for beginners. Today, let's take a look at what happened when this fell to the ground, and talk about the pointing principle of this in detail. From now on, we will no longer break our hearts for this pointing.

Opening

First of all, we all know that this is a keyword of Javascript language.

It represents an internal object automatically generated when the function is running, and can only be used inside the function. The value of this will change with different situations where the function is used. However, there is a general principle, that is, the direction of this cannot be determined when the function is defined, and only when the function is executed can we determine who this is pointing to. In fact, the final direction of this is the object that calls its function. Then let's explore this problem step by step.

Exploration 1


function a() {
  var user = " Steamed chubby fish ";
  console.log(this.name); //undefined
  console.log(this); //Window
 }
 a();
 window.a();// The two results are the same 

As we mentioned above, this finally points to the object that calls its function, where a is actually pointed out by window object.

Exploration 2


var obj = {
  name: ' Steamed chubby fish ',
  f1: function () {
   console.log(this.name);// Steamed chubby fish 
  }
 };
 obj.f1();

Again, I emphasize that the direction of this can't be determined when the function is defined, and only when the function is executed can I determine who this is pointing to; The f1 function in this example this is called by the obj object, so the this here points to the obj object.

Exploration 3

If you want to thoroughly understand this, you must look at the next few examples


var obj = {
  a: 5,
  b: {
   a: 10,
   fn: function () {
    console.log(this.a); //10
   }
  }
 };
 obj.b.fn();

Isn't it said that this ultimately points to the object that calls its function? Why not point to the obj object here?

Three points need to be added here:

If a function has this in it, but it is not called by an object at the next level, then this points to window. If there is an this in a function and this function is called by an object of the upper level, then this points to the object of the upper level. If a function has an this in it, the function contains multiple objects. Although the function is called by the outermost object, this only points to the first level object above it.

Seeing this, I believe everyone has basically mastered the principle of this pointing, and then break it down again: the pointing of this can't be determined when the function is defined, and only when the function is executed can we determine who this points to. In fact, this finally points to the object that calls its function.

Here are several different uses of this

Constructor (new keyword) case


function Student() {
  this.name = ' Steamed chubby fish ';
 }
 var s1 = new Student();
 console.log(s1.name);//  Steamed chubby fish 

Here, the object s1 can point out name in function Student because new keyword can change the direction of this and point this this to object s1.


// new  The procedure executed by the keyword 
 1.  Create in the function body 1 An empty object .
 2.  Make the current this Point to this empty object .
 3.  Pass this Adds a key-value pair to the currently empty object .
 4.  Returns the object with all key-value pairs added to the external variable .

this pointing situation in timer


var num = 0;
 function Obj() {
  this.num = 1;
  this.getNum1 = function () {
   console.log(this.num);
  };
  this.getNum2 = function () {
   setInterval(function () {
    console.log(this.num);
   }, 1000);
  };
 }
 var o = new Obj();
 o.getNum1();//1  (o.num)
 o.getNum2();//0 (window.num)

o.getNum2() The value is 0, which is where the this Point window , and then come up with our this pointing principle explanation: this The direction of the function is uncertain when the function is defined, but can only be determined when the function is executed this Who does it point to? In fact, this Ultimately points to the object that calls the function in which it is located.

Solution: this.num The function is timer setInterval Inside function () { console.log(this.num);} According to the this pointing principle, when the function is executed, this points to its upper level 1 object. setInterval , and because setInterval Yes window It was pointed out, so this Point window .

call , apply , bind Change the direction


var num = 0;
 function Obj() {
  this.num = 1;
  this.getNum1 = function () {
   console.log(this.num);
  };
  this.getNum2 = function () {
   setInterval(function () {
    console.log(this.num);
   }.bind(this), 1000);// Utilization bind Will this Bind to this function 
  };
 }
 var o = new Obj();
 o.getNum1();//1  (o.num)
 o.getNum2();//1 (o.num)
 

Explanation:

The bind () method is a method on Function. prototype. When called by the bound function, the bind method creates a new function with the first argument as the this of the runtime of the new function.

According to the principle:

Not used bind Method: When called: this.num Points to the object that calls the function in which it is located, that is, window.setTimeout Object. Use bind Method: When called: sets the original this Re-point to → call getSum2 Function (that is, the new this The function in which the function is located. The constructor here passes the new Called, so it points to an o object.

bind Method is more commonly used in this situation, of course if you use call Or apply Method, and the result is correct, but call And apply The method executes immediately after it is called, so there is no delay effect and the timer is meaningless.

The above is the detailed explanation of this pointing problem in JavaScript. Please pay attention to other related articles on this site for more information about JavaScript this pointing!


Related articles: