Kokodoko
Kokodoko

Reputation: 28148

Which variables are available inside an anonymous function?

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

Answers (2)

BenM
BenM

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

Denys Séguret
Denys Séguret

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

Related Questions