Function

Specifies a string of JavaScript code to be compiled as a function. Function is a core object.

Created by

The Function constructor:

new Function (arg1, arg2, ... argN, functionBody)

Parameters

arg1, arg2,...argn

(Optional) Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm".

functionBody

A string containing the JavaScript statements comprising the function definition.

Description

Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.

In addition to defining functions as described here, you can also use the function statement, as described in the JavaScript Guide.

Examples

The following code assigns a function to the variable activeSection.name. This function sets the current document's section name.

	var changeName = new Function("activeSection.name='sales'")

To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the changeName variable:

	var newName="sales"

	if (newName=="sales") {newName()}
	function changeName() {

      activeSection.name='sales'
	}

Assigning a function to a variable is similar to declaring a function, but they have differences:

When you assign a function to a variable using var changeName = new Function("..."), changeName is a variable for which the current value is a reference to the function created with new Function().

When you create a function using function changeName() {...}, changeName is not a variable, it is the name of a function

Specifying arguments in a Function object

The following code specifies a Function object that takes two arguments.

	var multFun = new Function("x", "y", "return x * y")

The string arguments "x" and "y" are formal argument names that are used in the function body, "return x * y".

The following code shows a way to call the function multFun:

	var theAnswer = multFun(7,6)
	Console.Write("15*2 = " + multFun(15,2))