contents   index   previous   next



Simulated named parameters

 

The properties of object data types may be used like named parameters. The following line simulates named parameters in a call to a function (note the use of curly braces {}):

 

var area = RectangleArea({length:4, width:2});

 

The following line uses traditional ordered parameters:

 

var area = RectangleArea(4, 2);

 

The following function definition receives the named and ordered parameters in the lines above. The definition allows for named or ordered parameters to be used.

 

function RectangleArea(length, width)

{

   if (typeof(length) == "object")

   {

      width = length.width;

      length = length.length;

   }

   return length * width;

} //RectangleArea

 

The function above could be rewritten as:

 

function RectangleArea(length, width)

{

   if (typeof(arguments[0]) == "object")

   {

      width = arguments[0].width;

      length = arguments[0].length;

   }

   return length * width;

} //RectangleArea

 

Either function definition works the same. The choice of one over the other is a matter of personal preference.

 

Though JavaScript allows many variations in how objects may be used, this straightforward example illustrates the essence of simulating named parameters in JavaScript. See the section "Named parameters in JavaScript" in the ScriptEase Tutorial for a detailed discussion about simulating named parameters in JavaScript.

 


Function property arguments[]