Archive for September, 2009

“Keeping” calling-context with setTimeout/setInterval

The javascript setTimeout function allows to pass some code or function to be called after a specifiec timeout in milliseconds. But since the callback is handled by the Window object it’ll loose the “this” from whatever it was called from. There’s two possible solutions to this, the first and most common is to use something like

var self = this;
setTimeout( function(){
     self.someValue = ........;
     self.someFunction();
     etc....
}, 500 );

But one other option is to execute the anonymous function which then returns another function as the code below shows.

function Foo(){
	setTimeout( (function(self){
		return function(){
			alert(this);	//Window
			alert(self);	//Foo
		}
	})(this), 2500 );
}
Foo.prototype.toString = function(){
	return "[object Foo]";
}
new Foo();

, ,

No Comments