05. Function Constructor
The Function
constructor creates a new Function
object. Calling the constructor directly can create functions dynamically, but suffers from security and performance issues similar to eval
.
Expression new Function(arg1, arg2, ..., argN, bodyString)
creates a new function:
The arguments
arg1, args2, ..., argN
passed to constructor become the parameter names for the new functionthe last argument
bodyString
is used as the function body code.
The functions created this way don't have access to current scope, thus closures cannot be created. They are always created in the global scope. One possible application of new Function is a better way to access the global object in a browser or NodeJS script:
Important to remember about new Function
is that almost never functions should be declared this way. Because the function body is evaluated on runtime, this approach inherits many eval()
usage problems: security risks, harder debugging, no way to apply interpreter optimizations, no code auto-complete.
Last updated
Was this helpful?