0

Since the global execution context will be popped out of the call stack after executing line number 2 and after 4 seconds if we examine the call stack we will have the execution context of the callback function alone which is dumped by setTimeout function.

So , how is it that still we are able to access "this.y" inside this function? Isnt it the fact that at line number 3 "this" points to the global execution context which will be out of scope by that time?

line 1: var y= 20;
line 2: setTimeout(function() {
line 3: console.log(this.y);
    }, 4000);
user1907849
  • 960
  • 4
  • 19
  • 42
  • With this particular case, there's no `this` needed at all. `y` is available simply as `y` inside the callback. – deceze Jan 04 '21 at 15:41
  • I did not explicitly passed this to callback function but still I am able to access , how is this happening? – user1907849 Jan 04 '21 at 15:47
  • In non-strict mode, `this` inside a "normal" function, called as a function, will refer to the global object. The global environment and the global object will always exist. – Felix Kling Jan 04 '21 at 15:51
  • `y` is a global variable (in the example code), it can also be referred by `window.y`, or `this.y` when `this` refers to `window`. – Teemu Jan 04 '21 at 15:52
  • Thanks for your comments , but my question was since the global execution context will be destroyed after line number 4 (call stack becomes empty), will the window object be still alive to be accessed in callback function? – user1907849 Jan 04 '21 at 15:56
  • 2
    I think you're mixing _execution context_ and _lexical environment record_ here, as Felix said, "_The global environment and the global object will always exist_". – Teemu Jan 04 '21 at 16:09

0 Answers0