How to execute a method passed as parameter to function

Muhammad Ummar picture Muhammad Ummar · May 14, 2011 · Viewed 84.4k times · Source

I want to write my own function in JavaScript which takes a callback method as a parameter and executes it after the completion, I don't know how to invoke a method in my method which is passed as an argument. Like Reflection.

example code

function myfunction(param1, callbackfunction)
{
    //do processing here
    //how to invoke callbackfunction at this point?
}

//this is the function call to myfunction
myfunction("hello", function(){
   //call back method implementation here
});

Answer

lonesomeday picture lonesomeday · May 14, 2011

You can just call it as a normal function:

function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction();
}

The only extra thing is to mention context. If you want to be able to use the this keyword within your callback, you'll have to assign it. This is frequently desirable behaviour. For instance:

function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction.call(param1);
}

In the callback, you can now access param1 as this. See Function.call.