Runtime-generated functions
Generate executable behavior from code supplied at runtime in a controlled environment.
JavaScript · Class
The Function() constructor dynamically creates a callable Function object from parameter names and a function-body string. It runs in the global scope rather than capturing the local scope where it was created.
The Function constructor builds a new function by treating every argument except the last as a parameter name and the final argument as the function body. The resulting function is parsed at construction time and runs with access only to its own scope and global scope, not the local scope where it was created.
new Function(functionBody)
new Function(arg1, functionBody)
new Function(arg1, arg2, functionBody)
new Function(arg1, arg2, /* …, */ argN, functionBody)
Function(functionBody)
Function(arg1, functionBody)
Function(arg1, arg2, functionBody)
Function(arg1, arg2, /* …, */ argN, functionBody)| Name | Type | Description |
|---|---|---|
arg1 … argN | string | One or more strings naming the function parameters; each argument before the final argument contributes a parameter name. |
functionBody | string | TrustedScript | JavaScript statements forming the function body; it may be a string or TrustedScript. |
A new Function instance.
const multiply = new Function("a", "b", "return a * b");
console.log(multiply(3, 4)); // 12Creates a function from parameter names and a function-body string, then invokes it.
Generate executable behavior from code supplied at runtime in a controlled environment.
Build a callable function when parameter names and implementation text are produced programmatically.
Function() creates a new Function object from strings. Arguments before the final one become parameter names, while the final argument becomes the function body.
Follow-up: What happens if it is called without new? It has the same effect: both forms create a new Function instance.
Unlike eval, a function created this way executes only in the global scope. It therefore cannot access local bindings from the constructor's surrounding scope.
Follow-up: Can it access variables declared inside itself? Yes; its own parameters and local declarations remain available during execution.
The constructor parses the supplied function when the Function object is created. Static declarations and expressions are generally more efficient because they are parsed with the surrounding code.
Follow-up: What is the main security concern? Untrusted input can become executable JavaScript, so dynamic construction should be avoided for such input.
Function.prototypeFunction.prototype.apply()Function.prototype.bind()Function.prototype.call()eval()function expression