Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
}
like image 899
Kyle Avatar asked Jul 13 '10 15:07

Kyle


3 Answers

funct.call(objThatWillBeThis, arg1, ..., argN);

or

funct.apply(objThatWillBeThis, arrayOfArgs);
like image 41
Vivin Paliath Avatar answered Oct 07 '22 22:10

Vivin Paliath


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, 

}
like image 42
Jake Avatar answered Oct 07 '22 22:10

Jake


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.

like image 182
meder omuraliev Avatar answered Oct 07 '22 23:10

meder omuraliev