Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a method passed as parameter to function

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 }); 
like image 272
Muhammad Ummar Avatar asked May 14 '11 10:05

Muhammad Ummar


People also ask

How do you pass a function as a parameter to another function?

Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.

Can we pass a function as a parameter in for function?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.


1 Answers

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.

like image 73
lonesomeday Avatar answered Oct 06 '22 07:10

lonesomeday