8.9. The Function() ConstructorAs explained earlier, functions are usually defined using the function keyword, either in the form of a function definition statement or a function literal expression. Functions can also be defined with the Function() constructor. Using the Function() constructor is typically harder than using a function literal, and so this technique is not commonly used. Here is an example that creates a function with the Function() constructor: var f = new Function("x", "y", "return x*y;"); This line of code creates a new function that is more or less equivalent to a function defined with the familiar syntax: function f(x, y) { return x*y; } The Function() constructor expects any number of string arguments. The last argument is the body of the function; it can contain arbitrary JavaScript statements, separated from each other by semicolons. All other arguments to the constructor are strings that specify the names of the parameters to the function being defined. If you are defining a function that takes no arguments, you simply pass a single stringthe function bodyto the constructor. Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. Like function literals, the Function() constructor creates anonymous functions. There are a few points that are important to understand about the Function() constructor:
|