One of the most common references to this is that it always refers to the object calling it, ignoring the context of this

Again, context

In the context section, we said that at this stage, the execution context creates the variable object, determines the scope chain, and points to this

In the section of variable object, we said that in the function call stack, if the current execution context is at the top of the stack, it means that the current context is active and the context is in the execution phase, and the variable object at this time is called active object (AO). The live object contains all of the attributes of the variable object, and all of the attributes are assigned, and the live object also contains the this pointer

To sum up:

  • The reference to this is context-dependent
  • Due to theActive objectsIt also contains the this pointer, so it can be accessed in the scope chainthis
  • This refers to the functionIt can only be confirmed when called, but not when defined
  • It is also worth noting that the value of this is an object

❗️❗️ Therefore, we should analyze the direction of this from different contexts

The runtime environment in JavaScript mainly includes the following three situations

  • Global environment: The global environment is the first place the code enters when it runs
  • Function environment: When a function is called to execute, the executing code in the current function is entered
  • Eval environment: Not recommended, not introduced

Global context

How does the global context determine that this refers to

In both non-strict and strict modes this refers to the top-level object (window in the browser).

For example 🌰 :

this= = =window // true

Copy the code
'use strict'

this= = =window;

this.name = 'vnues';

console.log(this.name); // vnues

Copy the code

Function context

How does the function context determine that this refers to

If this is the context of this then the reference to this should be determined by how the function is called

The function’s this is bound when the function is called, depending entirely on where the function is called (that is, how the function is called). To figure out what this points to, you have to know how the related function is called.

Independent call

Fun (), the function is called independently, in non-strict mode this refers to window, in strict mode this refers to undefined

For example 🌰:

const test = {

  outerfunction ({

    function inner({

      // This points to the window

      console.log(this);

    }

    inner();

  }

}

test.outer()



'use strict'

const test = {

  outerfunction ({

    function inner({

      // This points to undefined

      console.log(this);

    }

    inner();

  }

}

test.outer() // undefined

Copy the code

For the above 👆 code, it may be very dizzy at first, but we can judge according to the above concept that the call of inner function belongs to independent call, so we can judge it according to the rules of independent call

❗❗❗️ Note that the inner context of this function is the inner context of this function, and then how is the function called

The method call

When a function is called as a method of an object (an attribute of the object), this refers to that object;

For example 🌰:

var name = Lo Lo Lo Lo Lo Lo Lo Lo;

var doSth = function(){

    console.log(this.name);

}

var student = {

    name'vnues'.

    doSth: doSth,

    other: {

        name'other'.

        doSth: doSth,

    }

}

student.doSth(); // 'vnues'

student.other.doSth(); // 'other'

Copy the code

Constructor call

New Fun(), for the new operation, look at the new mock implementation in the previous section. This refers to the new object, which is the instantiated object

For example 🌰 :

// Create a constructor named Person that constructs an object with user and age

            const Person = function (user,age{

                this.user = user;

                this.age = age; 

            };



            // Construct a Person instance and test it

            const shane = new Person ('shane'.25);

            console.log(shane.user);//shane

            console.log(shane.age);/ / 25

Copy the code

Call, apply, bind

func.call(obj,value1,value2);

Copy the code
Func. Apply (obj, [value1, value2]);

Copy the code
 func.bind(obj,value1,value2)()

Copy the code

Dynamically change this to point to obj

For example 🌰 :

const value = 2;



const obj = {

    value1

}

function bar(name, age{

    console.log(this.value);

    return {

        valuethis.value,

        name: name,

        age: age

    }

}

bar.call2(null); / / 2

console.log(bar.call2(obj, 'kevin'.18));

Copy the code

Arrow function call pattern

Especially noteworthy. The point of this object is mutable, but in arrow functions, it is fixed. This pointing is static because of the arrow function (this pointing is determined when the code is written, not when the function is called).

So who does this of the arrow function point to ❓

MDN: Arrow functions do not create their own this, they only inherit this from the upper level of their scope chain

As we analyzed above at 👆, since the active object holds this, the scope chain can access the upper level of this

For example 🌰:

this.x = 9

function Module(x{

  this.x=x

  this.getX=(a)= >

     console.log(this)

     return this.x;

  }

};

const module = new Module(81)

module.getX(); / / 81



const retrieveX = module.getX;

retrieveX();   

Copy the code

conclusion

The following points should be noted when analyzing this:

  • The currentThis placeThe context in which the
  • According to the rules of its context, and then analyze the direction of this, it can not be one-sidedIt always points to the object that called it

JS this refers to MDN