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

+2


source to share


4 answers


JavaScript doesn't actually require you to pass all the parameters to a function. Or any parameters. Or you can pass more parameters than function names in this signature.

If the function defines a parameter, obj, but you just call it



otherfunction();

      

Then obj is just undefined.

+1


source


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

+2


source


Can't get function signature in JavaScript. However, you can simply pass any arguments you need and the function will ignore them if they don't need them. This will not result in an error.

+1


source


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

.)

+1


source







All Articles