Source: this

In most cases, how the function is called determines the value of this. This cannot be assigned during execution, and its value may vary each time the function is called.

Important: How a function is called determines the value of this, which means that most of the time this refers to the object on which it was called

This. XXX is undefined. This. XXX is undefined. Is that sometimes this in the context of code execution is not the object we take for granted.

ES5 introduced the bind method to set the value of this in functions, regardless of how the function is called. ES6 introduces arrow functions that do not provide their own this binding

We can use globalThis directly to get global objects anywhere

function someFunction() {
  return this;
}

// `true`:
console.log(someFunction() === globalThis);
Copy the code

This is bound to the execution context, so this can be divided into three types:

  • This in the global context
  • This in the context of a function
  • This in eval (rarely used)

In most cases, there are some special cases that need to be noted separately:

  1. Arrow function: Same as the external this
const outerThis = this
const arrowFunction = () = > {
  console.log(this === outerThis)
}
arrowFunction()		// true
Copy the code

Some other cases:

  • Bind: does not change the this pointer

  • Call /apply: does not change the this reference

  • Called as a property of another Object: does not change the this pointer

    const obj = {arrowFunction};
    // `true`
    obj.arrowFunction();
    Copy the code
  • Call a function with new:

    new arrowFunction()  
    // TypeError: arrowFunction is not a constructor
    Copy the code
    • Class uses the arrow function: this always points to an instance of class
    class Whatever {
      someMethod = () = > {
        // always refer to Whatever instances
        console.log(this);
      };
    }
    Copy the code

    In general, if the arrow function is used, the this inside the function basically points to the external this

  1. New: equivalent to object.create (Whatever. Prototype)

    • Bind: This reference will not be changed

      const BoundMyClass = MyClass.bind({foo: 'bar'});
      new BoundMyClass();
      Copy the code
    • New: this is pointed to as a property of another Object and is not changed

      const obj = {MyClass};
      // Logs `true` - parent object is ignored:
      new obj.MyClass();
      Copy the code
  2. Use call Apply bind

    • Call Apply can specify a this value and call a function with one or more arguments
    • Bind creates a new function whose this is specified

Reference article: What is this