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
}
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,
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With