Sobes.tech
Middle

What does the execution context value of `this` depend on in JavaScript?

sobes.tech AI

Answer from AI

The value of this in JavaScript depends on how the function is called. Main scenarios:

  1. Global context: Outside functions in strict mode ('use strict') this equals undefined. Without strict mode — the global object (window in browsers, global in Node.js).

  2. Object method call: this points to the object to which the called method belongs.

    const obj = {
      prop: 'value',
      method: function() {
        // this === obj
        console.log(this.prop);
      }
    };
    obj.method();
    
  3. Regular function call: In strict mode this equals undefined. Without strict mode — the global object.

    function myFunction() {
      // in strict mode this === undefined
      // without strict mode this === window (in browsers)
      console.log(this);
    }
    myFunction();
    
  4. Constructor (new): When using the new operator with a constructor function, this inside the function refers to the new object being created.

    function MyClass(name) {
      this.name = name; // this === new object
    }
    const instance = new MyClass('test');
    // instance.name === 'test'
    
  5. Explicit binding (call, apply, bind): Methods call, apply, and bind allow explicitly setting the value of this for a function.

    • call(thisArg, arg1, arg2, ...): Calls the function, setting this to thisArg and passing arguments separately.
    • apply(thisArg, [argsArray]): Calls the function, setting this to thisArg and passing arguments as an array.
    • bind(thisArg): Returns a new function with this permanently bound.
    const anotherObj = { value: 42 };
    function showValue() {
      console.log(this.value);
    }
    showValue.call(anotherObj); // Outputs 42
    
  6. Arrow functions (=>): Arrow functions do not have their own this. The value of this inside an arrow function is inherited from the lexical scope (the surrounding context) where it was defined.

    const outerObj = {
      name: 'Outer',
      method: function() {
        const arrowFunc = () => {
          // this is inherited from method, called as a method of outerObj
          console.log(this.name);
        };
        arrowFunc();
      }
    };
    outerObj.method(); // Outputs 'Outer'
    
    const anotherArrowFunc = () => {
        // this is inherited from the global context (or undefined in strict mode)
        console.log(this);
    };
    anotherArrowFunc();
    
  7. Event handlers in DOM: In most cases, this in an event handler refers to the DOM element on which the event occurred.

    // Example in a browser
    const button = document.querySelector('button');
    button.addEventListener('click', function() {
      // this === button
      console.log(this.tagName);
    });
    

Understanding these mechanisms is critical for the correct use of this in JavaScript.