Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a variadic function inside a variadic function in Javascript?

I have two function a() and b(), both are variadic functions, let say when I call function a() like this :

a(arg0, arg1, arg2, arg3, ...., argn);

then the function b() will be called as well inside a(), but without the first argument "arg0" in the arguments list of a() :

b(arg1, arg2, arg3, ...., argn);

Is there any way for it?

like image 258
Teiv Avatar asked Jul 24 '11 18:07

Teiv


People also ask

Can we pass a variable number of arguments to a function?

To call a function with a variable number of arguments, simply specify any number of arguments in the function call. An example is the printf function from the C run-time library. The function call must include one argument for each type name declared in the parameter list or the list of argument types.

What is variadic function in Javascript?

A variadic function is a function where the total number of parameters are unknown and can be adjusted at the time the method is called. The C programming language, along with many others, have an interesting little feature called an ellipsis argument.

How do you use variadic arguments?

It takes one fixed argument and then any number of arguments can be passed. The variadic function consists of at least one fixed variable and then an ellipsis(…) as the last parameter. This enables access to variadic function arguments. *argN* is the last fixed argument in the variadic function.

What happens to any extra parameters passed in to a JS function?

You can call a Javascript function with any number of parameters, regardless of the function's definition. Any named parameters that weren't passed will be undefined.


1 Answers

Every JavaScript function is really just another "object" (object in the JavaScript sense), and comes with an apply method (see Mozilla's documentation). You can thus do something like this....

b = function(some, parameter, list) { ... }

a = function(some, longer, parameter, list)
{
   // ... Do some work...

   // Convert the arguments object into an array, throwing away the first element
   var args = Array.prototype.slice.call(arguments, 1);

   // Call b with the remaining arguments and current "this"
   b.apply(this, args);
}
like image 179
Adam Wright Avatar answered Oct 23 '22 06:10

Adam Wright