Sobes.tech
Middle

What happens if you call `this` inside an arrow function?

sobes.tech AI

Answer from AI

In an arrow function, this is lexically bound. This means that this will refer to the execution context in which the arrow function was defined, not the context in which it was called.

Example:

const obj = {
  name: 'Object',
  method: function() {
    // here, `this` refers to obj
    const arrowMethod = () => {
      // here, `this` also refers to obj,
      // because the arrow function is defined inside method
      console.log(this.name);
    };
    arrowMethod();
  },
  anotherMethod: () => {
    // here, `this` refers to the global object (window in browsers)
    // because the arrow function is defined at the top level inside obj
    console.log(this);
  }
};

obj.method(); // Outputs "Object"
obj.anotherMethod(); // Outputs Window (in browsers)

Comparison with regular functions:

In regular functions, the value of this is determined by how the function is called (for example, using call, apply, bind, or as a method of an object).

const regularFunction = function() {
  console.log(this);
};

const context = { value: 42 };

regularFunction(); // `this` refers to the global object (window/globalThis)
regularFunction.call(context); // `this` refers to `context`

Thus, when calling this inside an arrow function, you get the value of this from the scope where the function was created, not where it was executed. This makes arrow functions useful for callbacks where maintaining the this context is often necessary.