today I’ve read we have a way of declaring the function by Function constructor. But I never seen the actual implementation that uses Function constructor in real. So I would like to ask, are there any circumstances that we can get benefit by using Function constructor as opposed to using function() declaration? And what are the hidden differences of between?(if there is any)
Function Constructor
var func = new Function("x", "y", "return x*y;"); // pass the context by String
function():
var func = function(x, y){ return x*y; }
Thanks
The Function constructor is a form of
eval, which should generally be avoided (it’s slow and considered insecure). There is really no benefit to using the Function constructor over the built in function statement unless you want to construct a function from dynamic components, which is pretty rare. There are legitimate uses for this form, however most of the time it’s used unnecessarily which is why it’s looked down upon and generally avoided.Also, functions created with the function constructor will not keep a reference to the environment they were defined in (the closure). When executed, they will pull those variables directly from the global scope.
Whereas regular functions do keep a reference to the environment in which they were defined: