简体   繁体   中英

Javascript - how do i set the 'this' variable for a function

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
}

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM