As all other objects,
Function objects can be created using the
new Function ([arg1[, arg2[, ... argN]],] functionBody)
arg1, arg2, ... argN
theValue", or "
Function constructor as a function (without using the
new operator) has the same effect as invoking it as a constructor.
Function objects created with the
Function constructor 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 parsed only once.
Specifying arguments with the
The following code creates a
Function object that takes two arguments.
var multiply = new Function("x", "y", "return x * y");
The arguments "
x" and "
y" are formal argument names that are used in the function body, "
return x * y".
The preceding code assigns a function to the variable
multiply. To call the
Function object, you can specify the variable name as if it were a function, as shown in the following examples.
var theAnswer = multiply(7, 6); var myAge = 50; if (myAge >= 39) myAge = multiply(myAge, .5);
caller : Specifies the function that invoked the currently executing function.
constructor: Specifies the function that creates an object's prototype.
length: Specifies the number of arguments expected by the function.
name : The name of the function.
prototype: Allows the addition of properties to function objects (both those constructed using
Function and those that were declared using a function declaration or a function expression).
apply: Allows you to apply the method of another object in the context of a different object (the calling object).
call: Allows you to call (execute) a method of another object in the context of a different object (the calling object).
Example: Creating "focus" and "blur" event handlers for a frame
The following example creates
onBlur event handlers for a frame. This code exists in the same file that contains the
frameset tag. Note that scripting is the only way to create "focus" and "blur" event handlers for a frame, because you cannot specify the event handlers in the
var frame = frames; frame.onfocus = new Function("document.body.style.backgroundColor = 'white';"); frame.onblur = new Function("document.body.style.backgroundColor = '#bbbbbb';");