0

I'm trying to understand how the arrow function passed to setTimeout, remembers the value of this from the previous execution context. I know that the this value is looked up using lexical scoping rules when executing arrow functions. Does that mean the arrow function closes over variables and the this keyword?

var obj = {
  name: 'TestName',
  func: function() {
    console.log(this)
    setTimeout(() => console.log(this), 1000)
  }
}

obj.func() //{name: "TestName", func: ƒ}
ekbgh
  • 36
  • 3
  • In normal functions `this` is *not* looked up using lexical scoping rules. Arrow functions change this and save `this` in the closure. – Barmar Jun 27 '18 at 18:58
  • thanks Barmar, I corrected the statement about look up – ekbgh Jun 27 '18 at 19:12

2 Answers2

0

Actually the whole point of using the fat arrow notation is to inherit the parent scope. Main application of arrow functions is to pull down the parent scope. When we invoke a setTimeout the chain happens as follows-:

  1. Call goes into Call-Stack.
  2. It is transferred to Web-Browser api space, which waits till the interval time.
  3. Now after interval time is completed it'll be handled by Event-Loop which will transfer it to JS-queue.
  4. The command execution will wait till other items in queue finish executing and then it'll transfer the execution flow again to Call-Stack whenever it is empty.
  5. Now the command inside setTimeout will be executed.

    JS execution flow

Abhisar Tripathi
  • 1,569
  • 10
  • 21
0

Does that mean the arrow function closes over the this keyword?

Yes, that's exactly what happens.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375