views:

155

answers:

4

i'm having a function where i need to call another function which 'll we dynamic jus i know the function name.

like my function is

myfunction(obj){
otherfunction(?);
}

otherfunction maybe

otherfunction(obj){
}

or

otherfunction(){
}

i dono know whether to pass the parameter or not.

how can i call the method

+2  A: 

you can call javascript functions with any count 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 see all three method calls work although it is declared with 2 arguments

Ghommey
think you're missing a ", " to separate you args there ;)
Matt
saw that but thanks anyway :)
Ghommey
+1  A: 

There isn't any way to get a function signature in JavaScript. However, you can just pass any arguments you may need, and the function will ignore them if it doesn't need them. It won't cause an error.

Gabe Moothart
+1  A: 

JavaScript does not actually require you to pass all the parameters to a fucntion. Or any parameters. Or, you can pass more parameters than the function names in it's signature.

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

otherfunction();

Then obj is just undefined.

Matt
+1  A: 

You can get the list of arguments passed to your function regardless of what you put in your function signature by looking at the arguments local variable.

You can call a function with any number of arguments using the Function apply method.

So to create a wrapper function that passes all its arguments onto the wrapped function:

function myfunction() {
    otherfunction.apply(window, arguments);
}

Is this what you're trying to do?

(window is the value that this will be set to in the wrapped function; if you don't have a specific object you're calling a method on, the global window object is normally used.)

bobince

related questions