Reputation: 28148
There's a little something about scope I just keep getting confused about:
this.init = function(){
var t = this;
setTimeout(function(){
// why is t still available here?
t.initgame();
// but not this?
this.initgame();
}, 500);
}
this.initgame = function() {
// yada yada
}
I get that inside an anonymous function, scope is different that outside of it. But why, in the above example, is the variable "t" available inside the timeout function, while "this" is not working?
Upvotes: 0
Views: 75
Reputation: 53238
When the anonymous function runs, it is no longer running as a member function of init
, but rather a top-level function of window
. As a result, this.initgame()
has no meaning.
For example, running console.log(this)
inside the timeout function returns as follows:
Window {top: Window, window: Window, location: Location, external:...
When you use var t = this
, you assign reference to the current object, which works.
Upvotes: 2
Reputation: 382394
The problem is that setTimeout
is called with window
as scope.
Using a dedicated variable to store this
(t
) is a perfectly valid and usual solution.
On modern browsers, bind
is sometimes convenient :
setTimeout((function(){
// use this
}).bind(this), 500);
Upvotes: 3