Creating Java Script Dynamic or anonymous Functions at Runtime
By Stephen Bucaro
You may recall that a function is a block of code that performs a specific task. Sometimes
a function returns a value. In Java Script you code a function by using the keyword function,
followed by the function's name, followed by a list of parameters that get passed to the function
(enclosed in parenthesis), followed by the block of code that performs the task (enclosed in curly braces).
Another way to create a function is to have Java Script write the function code during execution.
Why would a program need to create a function at runtime? This could be used in a program
that allows the user to add functionality to the application during execution.
A function that is created at runtime is called a dynamic function. To create a dynamic
function, use the keyword new, followed by the keyword Function (Note use of
upper-case F in keyword Function when creating dynamic functions), followed by a list of
parameter values enclosed in quotes and separated by commas
("parameter1","parameter2","parameter3","statements"), the final entry in the list being the
statements that will execute when the function is called.
Shown below is an example of code for a dynamic function:
var calcVolume = new Function("height","width","depth","var vol = height * width * depth; return vol;");
var result = calcVolume(10,4,6);
The first line after the script block opening tag above is the declaration of the dynamic
function, placing a reference to it in a variable named calcVolume. The second line calls
the dynamic function using that variable name, placing the return value in a variable named
result. The third line uses the alert function to display the value in result.
Dynamic functions are sometimes called "anonymous functions" because, as you can see in the
code above, technically the function doesn't have a name. In this example, the name calcVolume
is the name of the variable that contains a reference or pointer to the function in
the computer's memory.
Another note about anonymous functions is, because their reference is contained in a variable,
their scope is the same as any variable declared at that same level. In other words, if the code
to create an anonymous function is within a function, that anonymous function disappears
upon exit of the function within which it was created.
More Java Script Code:
• Easy Java Script Code for Sideways Slide show
• Disable IE8 Accelerators on Your Website
• Easy Slide Show Code With Linked Slides
• Concatenating a String and Another Data Type
• Easy Picture Zoom Code
• Where Did the User Click?
• Using the Java Script Date Object