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);
要么
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,
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.