views:

3013

answers:

3

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.

+4  A: 

I think you're looking for call:

myFunction.call(obj, arg1, arg2, ...);

This calls myFunction with this set to obj.

There is also the slightly different method apply, that takes the function parameters as an array:

myFunction.apply(obj, [arg1, arg2, ...]);
sth
See section 15.3.4.3, 15.3.4.4 and 10.1.8 in ECMAScript Language Specification: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
some
Thank you very much... very helpful
+22  A: 
ForYourOwnGood
coooooool :)Why oh why didn't I know that?
naugtur
A: 

This made my day. Thank you!

Michael Mikowski