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 });
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With