0

Trying to pass multiple parameters to a variable function call..

function myFunction(myvar,time){
    alert(myvar);   
}

t_function = "myFunction";
t_params = "haha,hehe";
window[t_function](t_params);

I basically need to mimic this call

myFunction("haha","hehe");

I can't set a specific amount of params in the variable function call, like

// I will not know how many params a function will need.
window[t_function](t_params1,t_params2,etc);

Any ideas? I'm tempted to use eval.

------ ended up doing this -----

function myFunction(myvar1,myvar2){ alert(myvar1 + " and " + myvar2);

}

t_function = "myFunction";
t_params = [];
t_params[0] = "haha";
t_params[1] = "hehe";

window[t_function].apply(this,t_params);

thanks all, specially to Joseph the Dreamer

1
  • You can actually declare the array as var t_params = ['hello','world']; Commented Apr 26, 2013 at 3:29

2 Answers 2

2

You need apply, which takes in a value for this in your function, and an array of arguments:

window[t_function].apply(this,[arg1,arg2,...,argN]);

And the function will receive it as:

function myFunction(arg1,arg2,...,argN){...}

Every value passed into the invoked function can be accessed via the array-like arguments. This is useful especially when the arguments are dynamic. Thus, you can do something like:

function myFunction(){
  var arg1 = arguments[0]; //hello
  var arg2 = arguments[1]; //world
}

//different ways of invoking a function
myFunction('hello','world');
myFunction.call(this,'hello','world');
myFunction.call(this,['hello','world']);
Sign up to request clarification or add additional context in comments.

2 Comments

will that pass an array into my function? or arguments as if they were called directly myFunction(arg1,arg2) . because if that passes an array into the function then i have to mod my function to process array as parameters/arguments
@BrownChiLD updated the answer, and read the documentation for apply
1

If you can reliably use , as a separator, try this:

window[t_function].apply(null,t_params.split(","));

2 Comments

I think t_params is a string of variable names not values.
"i basically need to mimic this call myFunction("haha","hehe");" Strings, not variables ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.