function

The function object is the container for a series of JavaScript statements, which is used to call all of the statements using one command, instead of repeating all the statements contained within for every time you need them. Some may refer to this as Object Oriented Programming. The function object is declared, then the name of the function. The name of the function, with its parameters stated within parentheses, is the statement that is called when referencing the function. The executable statements for the function are contained within the opening and closing braces which follow. A function may have zero or more parameters specified, and may be any valid JavaScript data type, including object references and arrays. Variables declared outside a function are available to all preceeding functions, and are referred to as global variables. Variables declared within the function are available only to that function, and are referred to as local variables.



When using frames, you may have the need to use a function created in an adjacent frame. Since a function belongs to the document (HTML Page) it is created in, you must supply a reference to that frame, using the frame's name, as follows:

parent.frameName.functionName()

When referencing within a script an object within a function created within the same document, use the object name and an event handler (to tell the browser when to invoke the object), as in the following syntax example:

objectReference.eventHandler = functionName

Notice that the parentheses were left out of the function name. Using the parentheses with this method will result in the browser looking for a method called whatever function name you've chosen, which obviously will be a non-existent method.

syntax:

function functionName( [ parameterOne, [parameterTwo, [ parameterThree ] ] ] ) {

statements

}

A function may also be declared as a variable within another function, as follows:

var functionName = new function( [ parameterOne, [parameterTwo] , " statementOne", " statementTwo " ] )

EXAMPLE

function changeLinkColor() {

document.link = "red";

}

This simple function changes the color of the links within the page to the named color, red.



As you can see from the above syntax examples, a function may be also declared as a variable. The example which follows performs the same change as the above, more commonly used method.

var changeLinkColor = new function(document.link = "red");

The Properties of the function Object are:

• arguments

• arity

• caller

• length

• prototype

The Methods of the function Object are:

• toString()

• valueOf()

• call()