From the MDN description of Function
:
Function objects created with the Function constructor are parsed when
the function is created. This is less efficient than declaring a
function with a function expression or function statement and calling
it within your code, because such functions are parsed with the rest
of the code.
All arguments passed to the function are treated as the names of the
identifiers of the parameters in the function to be created, in the
order in which they are passed.
Note: Functions created with the Function constructor do not create
closures to their creation contexts; they always are created in the
global scope. When running them, they will only be able to access
their own local variables and global ones, not the ones from the scope
in which the Function constructor was called. This is different from
using eval with code for a function expression.
So, from this, you see the following differences when using new Function(...)
:
The code for the new function is a string and is parsed when the new Function(...)
is called, not when the page is parsed. For example, you can build a string and then use that as your function body.
These functions are always created in the global scope and do not create closures within the environment they are created in.
These functions cannot access parent scoped variables.
You can dynamically construct code and then have it turned into a parsed/live function - somewhat similar to eval()
, but with a few subtle differences.
Note: Because the function body with the new Function(...)
construct has to be contained in a Javascript string, it's messy to write most code this way. new Function(...)
should generally only be used for special circumstances where you need to construct a function body on the fly (which is likely a very rare case) and not where you know the code ahead of time.