In strict mode, this
should be undefined
inside of a non-method (a function):
see http://jsfiddle.net/jfp06nc9/1/
showing this
is undefined
However, when the setTimeout
is used, then this
is bound to window
:
see http://jsfiddle.net/jfp06nc9/2/
and http://jsfiddle.net/jfp06nc9/3/
showing that this === window
returns true.
so it looks like the function fn
passed to setTimeout
is invoked not as a function, but as a method, like window.fn()
or fn.call(window)
or (fn.bind(window))()
.
see http://jsfiddle.net/jfp06nc9/4/
showing the last 3 calls above would all show this === window
as true
.
Is that true? I can't find any specification about it so please include that in your answer.
(the jsfiddle was running in Chrome 46.0)
P.S. This question is NOT about what this
is bound to, but about, in non-strict mode, setTimeout
can run fn()
and the this
will be bound to window
. But in strict mode, if setTimeout
really runs it as fn()
, then this
should now be undefined
instead of window
, so there is a subtle difference there, that it seems setTimeout
runs it (or arrange to run it) not as fn()
but as fn.call(window)
The jsfiddle and code:
http://jsfiddle.net/jfp06nc9/7/
(function() {
"use strict";
setTimeout(function() {
"use strict";
console.log(this);
}, 1000);
}());
Since the function runs in strict mode, if it is run as a function, then this
should be undefined
but it is in fact window