JavaScript Examples

JavaScript Menu

Home

  

JavaScript Functions Primer

JavaScript function does not have to define the return type nor the types of the arguments. A simple function can be declared as follows:

function printString(str)
{
     alert(str);
}

As in Java, all primitives are passed by value, while objects are passed by reference. In JavaScript you can pass to the function more parameters than it declares as its formal arguments. In order to access parameters you use arguments array. Here is an example that prints out all arguments passed:

function printStrings()
{
     for (i=0; i<arguments.length; i++)
     {
         alert(argument[i]);
     }
}

The Function object can be used to create a new function out of a string and pre-compile it. Later, we can use JavaScript built-in capability for assigning pointers to functions. The Function object is a JavaScript 1.1 feature, but it should work in NS 2.0. Example:

var newFunction = new Function ("arg1", "arg2", "return arg1 * arg2;");
myCar.multiply = newFunction;

alert(myCar.multiply(2, 23));

The may as many arguments as necessary. The actual body of the function goes as the last argument. Function assignment may be used in many ways, including defining additional behavior for an object. This is similar to function pointers in C.

someObject.newMethod = otherObject.existingMethod;

No we can call someObject.newMethod() as if it were part of the object definition.