I have a function that performs a callback function. How to set the 'this' variable of a 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 }
you can execute the function in the context of the object using call :
fn.call( obj, 'param' )
There also apply
The only difference is the syntax for supplying arguments.
You can use apply () or call ( ).
Or you can execute the function with your choice of what this is inside the function. Apply accepts arguments for the function as an array, and call allows you to specify them separately.
this
Apply
call
funct.call(objThatWillBeThis, arg1, ..., argN);
or
funct.apply(objThatWillBeThis, arrayOfArgs);
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, }