setTimeout
is generally defined as window.setTimeout
in browsers, and can be called as just setTimeout
because it's available in the global scope.
That also means the context, and this
value, is always window
, unless another this
value is explicitly set.
MDN says
Code executed by setTimeout()
is called from an execution context
separate from the function from which setTimeout was called.
The usual rules for setting the this
keyword for the called function
apply, and if you have not set this
in the call or with bind, it
will default to the global (or window) object in non–strict mode, or
be undefined in strict mode.
It will not be the same as the this
value for the function that
called setTimeout.
MDN also outlines a number of ways to solve the "this-problem" in setTimeout
.
Personally I think I would just take the easy way out, and use a variable
Greeter.prototype.delayed_greet = function() {
var that = this;
setTimeout( function cb() {
console.log(' Hello ' + that.name);
}, 500);
};
Another option would be an arrow function, as they keep the surrounding context and don't create their own context.
var o = {
fn () {
setTimeout( () => { console.log(this) }, 500)
}
}
var o2 = {
fn () {
setTimeout( function() {
console.log(this === window)
}, 1000)
}
}
o.fn(); // fn() --- arrow function
o2.fn(); // true, is window --- regular function