Sobes.tech
Middle

Räägi sellest erinevates kontekstides: objektimeetodites, noolefunktsioonides ja tavalistes funktsioonides.

sobes.tech AI

Vastus AI-lt

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 the way it is called:
    • In strict mode ('use strict') — this will be undefined.
    • In non-strict mode — it will be the global object (window in browsers).
function foo() {
  console.log(this);
}
foo(); // window or `undefined` in strict mode
  • In arrow functions this is lexically inherited from the outer context, i.e., taken from the scope where the function was declared, not where it is called:
const obj = {
  name: 'Bob',
  arrowFunc: () => {
    console.log(this.name);
  },
  regularFunc() {
    const arrow = () => {
      console.log(this.name);
    };
    arrow();
  }
};
obj.arrowFunc(); // undefined or name from external context
obj.regularFunc(); // Bob

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