Sobes.tech
Middle

Tell about this in different contexts: in object methods, in arrow functions, and in regular functions.

sobes.tech AI

Answer from AI

In JavaScript, the value of this depends on the call context of the function:

  • In object methods this refers to the object to which the method belongs:
const obj = {
  name: 'Alice',
  greet() {
    console.log(this.name);
  }
};
obj.greet(); // Alice
  • In a regular function (not a method), this depends on the mode and call method:
    • In strict mode ('use strict') — this will be undefined.
    • In non-strict mode — the global object (window in browsers).
function foo() {
  console.log(this);
}
foo(); // window or undefined in strict mode
  • In an arrow function this is lexically inherited from the outer context, meaning it is taken from the scope where the function was declared, not called:
const obj = {
  name: 'Bob',
  arrowFunc: () => {
    console.log(this.name);
  },
  regularFunc() {
    const arrow = () => {
      console.log(this.name);
    };
    arrow();
  }
};
obj.arrowFunc(); // undefined or name from outer context
obj.regularFunc(); // Bob

Thus, arrow functions are convenient for preserving the this context from an outer function, while regular functions and methods have their own this value depending on how they are called.

Tell about this in different contexts: in object… - sobes.tech