Ivan Zuzak home about blog projects talks & papers other

Named arguments in JavaScript

09 Aug 2009

While working on another project (pmrpc, which I will write about soon), the implementation of a feature came down to calling JavaScript functions with named arguments. Unfortunately, the JavaScript language (or EcmaScript to be exact) doesn't support named arguments, rather only positional arguments.

Usually, JavaScript developers get around this by defining functions to accept a single object argument which acts like a container for all other named parameters:

 1 // params is a container for other named parameters
 2 function callMe(params) {
 3   var param1 = params['param1'];
 4   var param2 = params['param2'];
 5   var param3 = params['param3'];
 7   // do something...
 8 }
10 var result = callMe({ 'param3' : 1, 'param1' : 2, 'param2' : 3 });

This solution works nicely when you are in the position to modify every function to be called this way. However, this is not always the case (e.g. when using external libraries), and also isn't as readable as having a proper parameter list, and introduces code overhead in every function that implements this principle. What I needed for my project is something that enables calling any JavaScript function with named arguments, without modifying the function itself.

What I came up with (code presented below) is based on the following:

  1. using the toString method of the Function prototype, it is possible to retrieve a string representation of any function definition
  2. from the string representation, it is possible to parse the number, order and names of function parameters
  3. from a dictionary of named arguments, it is possible to construct an array of arguments in the correct order using the parsed representation
  4. using the apply method of the Function prototype, it is possible to dynamically call a function, passing an array of arguments instead of an argument list.
 1 // calls function fn with context self and parameters defined in dictionary
 2 // namedParams
 3 function callWithNamedArgs( fn, self, namedParams ) {
 4   // get string representation of function
 5   var fnDef = fn.toString();
 7   // parse the string representation and retrieve order of parameters
 8   var argNames = fnDef.substring(fnDef.indexOf("(")+1, fnDef.indexOf(")"));
 9   argNames = (argNames === "") ? [] : argNames.split(", ");
10   var argIndexes = {};
11   for (var i=0; i<argNames.length; i++) {
12     argIndexes[argNames[i]] = i;
13   }
15   // construct an array of arguments from a dictionary
16   var callParameters = [];
17   for (paramName in namedParams) {
18     if (argIndexes[paramName]) {
19       callParameters[argIndexes[paramName]] = namedParams[paramName];
20     }
21   }
23   // invoke function with specified context and arguments array
24   return fn.apply(self, callParameters);
25 }
27 // example function
28 function callMe(param1, param2, param3) {
29   // do something ...
30 }
32 // example invocation with named parameters
33 var result = callWithNamedArgs(
34                callMe, this, { 'param3' : 1, 'param1' : 2, 'param2' : 3 });

This could also have been implemented as a Function prototype method and be called directly on a function object, which would simplify usage since the target function parameter wouldn't have to be passed. But, if the CallWithNamedArgs function indeed was implemented prototype function, could the context parameter be removed also? I.e. is it possible to retrieve the current execution context (this object) of the target function within the CallWithNamedArgs method? The problem is that the execution context within the CallWithNamedArgs method is the Function object on which the CallWithNamedArgs method was called. But what we need is the execution context of the target function, which is the Function object on which the CallWithNamedArgs method was called. That is, what we need is the current execution context of the parent object. Any ideas? @izuzak.