0

Why is the value of this in first example: this: myObject and document/window in the second example? If this is defined/evaluated when the function is called, then I dont understand it.

myObject = {
  myMethod: function () {
    helperObject.doSomethingAsync('superCool', () => {
      console.log(this); // this === myObject
    });
  },
};
const reusabledCallback = () => {
  console.log(this); // this === window or global object
};

myObject = {
  myMethod: function () {
    helperObject.doSomethingAsync('superCool', reusabledCallback);
  },
};
  • Does this answer your question? [What does "this" refer to in arrow functions in ES6?](https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6) – pilchard Dec 11 '22 at 11:46
  • also: [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions) and [How does the "this" keyword work, and when should it be used?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work-and-when-should-it-be-used) – pilchard Dec 11 '22 at 11:46

1 Answers1

0
  • this in an arrow function is the same this as the one in the outer scope where the function is defined.
  • this in a function declared with the keyword function is the object on which the function is being called.
  • this in the global scope is the window object (or the relevant global object)

In your first code, the arrow function containing this is defined inside a function, so this is whatever called that function (myObject in your case).

In your second code, the arrow function containing this is defined in the global scope, so this is the global object (window).

Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32
  • But isnt this evaluated when the function containing it is run? Then even if reusabledCallback is defined in the global scope, when its run, it is also then defined inside a function which is invoked by myObject so shouldnt that be the same? –  Dec 11 '22 at 12:04
  • 2
    @juliascoding No, `this` in an arrow function is the `this` at the place where the arrow function is defined, not where it's executed. – Guillaume Brunerie Dec 11 '22 at 12:14
  • ahh okay thank you! and this inside a function with function keyword is on the contrary is where its executed, right?! –  Dec 11 '22 at 12:58
  • 1
    Not really where it is executed, but *how* it is executed. If the function is called as `myObject.myMethod();`, then `this` inside the method will be `myObject`. If you do instead `const objectMethod = myObject.myMethod; objectMethod();`, then `this` inside the method will be `window`. – Guillaume Brunerie Dec 11 '22 at 13:23