this keyword locate at the core JavaScript language. It has some differences between strict mode and non-strict mode. in nonstrict mode, is refer to an object and in strict mode can be any value.

Main points:

  • The value of this is a property of an execution context (global, function or eval)
  • In most cases, the value of this is determined by how a function is called (runtime binding).
  • It can’t be set by assignment during execution, and it may be different each time the function is called.
  • In function execution context, it have been setup two parameters: this, and arguments keywords.
  • In an object method, this refers to the object.
  • In the global execution context (outside of any function), this refers to the global object whether in strict mode or not.
    • You can always easily get the global object using the global globalThis property, regardless of the current context in which your code is running.
  • Inside a function, the value of this depends on how the function is called(runtime binding).
    • In non strict mode, return a globe object:
      function f1() {
      return this;
      }
      // In a browser:
      f1() === window; // true
      // In Node:
      f1() === globalThis; // true
      
    • In strict mode, if the value of this is not set when entering an execution context, it remains as undefined:
      function f2() {
      'use strict'; // see strict mode
      return this;
      }
      f2() === undefined; // true
      

      The value of this is undefined, because f2 was called directly and not as a method or property of an object (e.g. window.f2())

  • inside a constructor function
    function person (name, age){
    this.name = name;
    this.age = age;
    }
    let tom = new person(Tom, 30);
    

    This refer to the new object ‘tom’. More info, go to new keyword topic.

  • In an event, this refers to the element that received the event.

  • Methods like call(), apply(), and bind() can refer this to any object.
    • ES5 introduced the bind() method to set the value of a function’s this regardless of how it’s called
  • In Arrow function
    • arrow functions don’t provide their own this binding (it retains the this value of the enclosing lexical context).
    • in regular function, ‘this’ keyword will represent the object which call the function. it can be a window , button or whatever.
    • in arrow function, ‘this’ will always represent the object which defined the arrow function.
  • in Class context, similar with function , but some differences:
    • Within a class constructor, this is a regular object;
    • All non-static methods within the class are added to the prototype of this.