Set "this" variable easily?

sam picture sam · Jan 19, 2009 · Viewed 62.3k times · Source

I have a pretty good understanding of Javascript, except that I can't figure out a nice way to set the "this" variable. Consider:

var myFunction = function(){
    alert(this.foo_variable);
}

var someObj = document.body; //using body as example object
someObj.foo_variable = "hi"; //set foo_variable so it alerts

var old_fn = someObj.fn;   //store old value
someObj.fn = myFunction;   //bind to someObj so "this" keyword works
someObj.fn();              
someObj.fn = old_fn;       //restore old value

Is there a way to do this without the last 4 lines? It's rather annoying... I've tried binding an anonymous function, which I thought was beautiful and clever, but to no avail:

var myFunction = function(){
    alert(this.foo_variable);
}

var someObj = document.body;        //using body as example object
someObj.foo_variable = "hi";        //set foo_variable so it alerts
someObj.(function(){ fn(); })();    //fail.

Obviously, passing the variable into myFunction is an option... but that's not the point of this question.

Thanks.

Answer

ForYourOwnGood picture ForYourOwnGood · Jan 19, 2009

There are two methods defined for all functions in JavaScript, call(), and apply(). The function syntax looks like:

call( /* object */, /* arguments... */ );
apply(/* object */, /* arguments[] */);

What these functions do is call the function they were invoked on, assigning the value of the object parameter to this.

var myFunction = function(){
    alert(this.foo_variable);
}
myFunction.call( document.body );