This section provides a tutorial example on how to define new functions with the Function object type constructor.
JavaScript provides Function as a built-in object type. The constructor of the Function type
has the following calling signature:
new Function("arg_1", "arg_2", ..., "function_body");
where the last parameter is a list o statements to form the body of the new function,
and all other parameters are names of parameters of the new function.
The tutorial example below shows you how to define new functions with the
Function object type constructor:
// Function_Constructor.js
// Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
// Defining a new function with no parameters
var hello = new Function(
"println(\"Hello World!\");"
)
// Calling the function
hello();
// Defining a new function with one parameter
var f2c = new Function("fahrenheit",
"println(\"Converting Fahrenheit = \"+fahrenheit);"
+ "var celsius = (fahrenheit - 32.0 ) / 1.8;"
+ "println(\"Returning Celsius = \"+celsius);"
+ "return celsius;"
)
// Calling the function
var received = f2c(212.0);
println("Received Celsius = "+received);
Run this JavaScript file with "jrunscript" in a command window, you will get:
Conclusion: The Function object type constructor works. But it is very hard to use, mainly because
the statements of the new function must be entered as a single string literal. All quotes in those statements
must be escaped with backslashes (\). It is still better to use the traditional way to define new functions
using the "function" statements.