When in strict mode, the value of this
should be undefined
inside a non-method (a function):
To see an example where this
is undefined
, visit http://jsfiddle.net/jfp06nc9/1/
However, if the setTimeout
function is used, then this
becomes bound to window
:
Check out examples at http://jsfiddle.net/jfp06nc9/2/ and http://jsfiddle.net/jfp06nc9/3/. In these cases, this === window
returns true.
It appears that the function fn
passed to setTimeout
is executed as a method rather than a function, like window.fn()
or fn.call(window)
.
Take a look at http://jsfiddle.net/jfp06nc9/4/ for more examples showing this === window
as true
.
Is this really true? If you have insights from any specification, please share them in your response.
(Note: The jsfiddle test was conducted on Chrome 46.0.)
P.S. This question does not revolve around what this
actually refers to; it is about how setTimeout
behaves differently in non-strict and strict modes when running fn()
.
For reference, here is the setTimeout
code snippet:
http://jsfiddle.net/jfp06nc9/7/
(function() {
"use strict";
setTimeout(function() {
"use strict";
console.log(this);
}, 1000);
}());
Given that the function runs in strict mode, the expectation is that if it is executed as a function, then this
should be undefined
. However, it evaluates to window