Javascript - Pass variable parameters to Function

Go To StackoverFlow.com

2

I am looking to be able to create two functions, BaseFunction and CallbackFunction where BaseFunction takes in a variable set of parameters as such:

BaseFunction(arg1, arg2, ....)
{
    //Call the Callback function here
}

and callback function receives the same parameters back:

CallbackFunction(value, arg1, arg2, ...)
{

}

How can I pass the parameters from the base function to the callback function?

2012-04-04 19:01
by mrK


7

Use apply to call a function with an array of parameters.

BaseFunction(arg1, arg2, ....)
{
    // converts arguments to real array
    var args = Array.prototype.slice.call(arguments);
    var value = 2;  // the "value" param of callback
    args.unshift(value); // add value to the array with the others
    CallbackFunction.apply(null, args); // call the function
}

DEMO: http://jsfiddle.net/pYUfG/

For more info on the arguments value, look at mozilla's docs.

2012-04-04 19:06
by Rocket Hazmat
This worked perfectly. Thanks - mrK 2012-04-04 19:55
You're welcome :- - Rocket Hazmat 2012-04-04 20:58


2

to pass arbitrary number of arguments:

function BaseFunction() {
     CallbackFunction.apply( {}, Array.prototype.slice.call( arguments ) );
}
2012-04-04 19:06
by abresas
You can actually just pass arguments to apply without calling slice on it - Rocket Hazmat 2012-04-04 19:13
@Rocket that won't necessarily work on all browsers. arguments is an Array-like object, but not an array. for example, firefox prior to version 4 had a bug that is now fixed that did not allow you to pass an arguments object. https://bugzilla.mozilla.org/show_bug.cgi?id=56244 - abresas 2012-04-04 19:45
True, though I'd hope people have the latest versions of their browsers. The Mozilla docs page for apply says you can pass an "array-like" object. EDIT: Never mind: "Note: Most browsers, including Chrome 14 and Internet Explorer 9, still do not accept array like objects and will throw an exception." - Rocket Hazmat 2012-04-04 19:50


0

This kind of does the trick:

BaseFunction(arg1, arg2, ....)
{
  CallbackFunction(value, arguments);
}

However CallbackFunction needs to accept array:

CallbackFunction(value, argsArray)
{
  //...
}
2012-04-04 19:04
by Tomasz Nurkiewicz
Yeah, that's my fallback right now. I'd prefer to have it done another way if possible - mrK 2012-04-04 19:05
Ads