Using the Function Constructor
This section provides a tutorial example on how to define new functions with the Function object type constructor.
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) 2013 by Dr. Herong Yang, 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);
Hello World! Converting Fahrenheit = 212 Returning Celsius = 100 Received Celsius = 100
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.
Table of Contents