Delegate in javascript
I have a function where I need to call another function that will dynamically jus, I know the name of the function.
as my function
myfunction(obj){ otherfunction(?); }
another function could be
otherfunction(obj){
}
or
otherfunction(){
}
Don't know if to pass the parameter or not.
how can i call the method
source to share
you can call javascript functions with any number of arguments:
function myFunction ( firstValue, secondValue )
{
if ( firstValue ) alert ( firstValue );
if ( secondValue ) alert ( secondValue );
}
myFunction (); //works but no alert
myFunction ("Hello");// 1 alert
myFunction ("Hello", "World");// 2 alerts
as you can see, all three method calls work even though they are declared with 2 arguments
source to share
You can get the list of arguments passed to your function, no matter what you specified in your function signature, by looking at the local variable arguments
.
You can call a function with any number of arguments using the Function method apply
.
So, to create a wrapper function that passes all of its arguments to the wrapped function:
function myfunction() {
otherfunction.apply(window, arguments);
}
Is this what you are trying to do?
( window
is the value to this
be set in the wrapped function; unless you have a specific object that you call the method on, the global object is usually used window
.)
source to share