I have a setTimeout defined inside of a function that controls the player’s respawn (i am creating a game):
var player = {
...
death:(function() {
this.alive = false;
Console.log("death!");
var timer3 = setTimeout((function() {
this.alive = true;
Console.log("alive!");
}),3000);
}),
...
}
When it executes, I read in the console, “death!” and 3 seconds later “alive!”. However, alive is never really set back to true, because if i write player.alive in the console, it returns false. How come i can see “alive!” but the variable is never set back to true?
You have to be careful with
this. You need to assign yourthisin the outer scope to a variable. Thethiskeyword always refers to thethisof the current scope, which changes any time you wrap something infunction() { ... }.This should give you better success.
Update 2019-10-09: The original answer is true, but another option is now available for recent versions of JavaScript. Instead of using
function, you can use an arrow function instead, which does not modifythis:This is supported from ES6 forward, which is part of all current browsers but IE (of course), I think. If you are using a modern framework to build your project via Babel or whatever, the framework should make sure this works as expected everywhere.