0

I know there are a ton of blogs and examples out there explaining the concept of this keyword in different scenarios and reading more and more is making it confusing for me.

In the below example, the output for both the setTimeout calls is same but I am sure not for the same reason

function x() {
  setTimeout(() => {
    console.log(this)
  }, 100);

  setTimeout(function() {
    console.log(this)
  }, 200);
}
x(); //logs window object twice

I know that

  1. The arrow functions inherit lexical scope i.e. the scope at which the parent object is defined
  2. The regular function gets its scope from the scope where it is called and not where it is defined.
  3. The context in which setTimeout() function runs is always window.

Can you please explain why both are logging the window object and correct me if my understanding is wrong.

Saksham
  • 8,110
  • 6
  • 35
  • 63
  • 1
    The `setTimeout` callback, if a full function, is called with the global `this`. A standalone function, when called plainly, like `x()`, also has its `this` as the global `this`. So the arrow function's `this` inherits from `x`'s `this`, which is the same as the `function` in the second's `setTimeout` – CertainPerformance May 06 '19 at 07:50
  • @CertainPerformance can you tell what does full function mean? – Saksham May 06 '19 at 07:54
  • `function` as opposed to `() =>` – CertainPerformance May 06 '19 at 07:54

0 Answers0