Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is window still defined in this strict mode code?

Tags:

javascript

"use strict";

setTimeout(function() {"use strict";console.log(this)}, 1000);

The 'this' inside functions called by setTimeout should refer to global object, but I also have "use strict"; in the body. Yet it logs window instead of undefined, which is what I was expecting. What's happening here?

like image 756
Zack Gao Avatar asked Sep 02 '25 10:09

Zack Gao


2 Answers

setTimeout is defined as calling the function it is passed in the context of window.

the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context,

It is akin to calling yourfunction.apply(window) not yourfunction().

like image 108
Quentin Avatar answered Sep 05 '25 01:09

Quentin


Now it's almost 4 years after the question.

There has been a note in MDN setTimeout page, which precisely addresses this question.

The default this value of a setTimeout callback will still be the window object, and not undefined, even in strict mode.

This applies to setInterval too, even though it is not mentioned there.

like image 31
themefield Avatar answered Sep 05 '25 02:09

themefield