tags:

views:

88

answers:

4

I have a function which takes a callback function. How can I set the 'this' variable of the callback function?

eg.

function(fn){
    //do some stuff
    fn(); //call fn, but the 'this' var is set to window
    //, how do I set it to something else
}
+13  A: 

you can execute a function in the context of an object using call:

fn.call( obj, 'param' )

There's also apply

Only difference is the syntax for feeding arguments.

meder
thanks! worked perfectly!
Kyle
+2  A: 

You can use either apply() or call().

Either allows you to execute a function with your choice of what this is inside the function. Apply takes the arguments for the function as an array, while call allows you to specify them individually.

Alex JL
+2  A: 
funct.call(objThatWillBeThis, arg1, ..., argN);

or

funct.apply(objThatWillBeThis, arrayOfArgs);
Vivin Paliath
+2  A: 

You can use either .call() or .apply(). Depending on your requirement. Here is an article about them.

Basically you want:

function(fn){
    //do some stuff
    fn.call( whateverToSetThisTo ); //call fn, 

}
Jake