Are eval() and new Function() the same thing?
Are these two functions doing the same thing behind the scenes? (in single statement functions)
var evaluate = function(string) {
return eval('(' + string + ')');
}
var func = function(string) {
return (new Function( 'return (' + string + ')' )());
}
console.log(evaluate('2 + 1'));
console.log(func('2 + 1'));
No, they are not the same.
-
eval()
evaluates a string as a JavaScript expression within the current execution scope and can access local variables. -
new Function()
parses the JavaScript code stored in a string into a function object, which can then be called. It cannot access local variables because the code runs in a separate scope.
Consider this code:
function test1() {
var a = 11;
eval('(a = 22)');
alert(a); // alerts 22
}
If new Function('return (a = 22);')()
were used, the local variable a
would retain its value. Nevertheless, some JavaScript programmers such as Douglas Crockford believe that neither should be used unless absolutely necessary, and evaling/using the Function
constructor on untrusted data is insecure and unwise.
new Function
creates a function that can be reused. eval
just executes the given string and returns the result of the last statement. Your question is misguided as you attempted to create a wrapper function that uses Function to emulate an eval.
Is it true that they share some code behind the curtains? Yes, very likely. Exactly the same code? No, certainly.
For fun, here's my own imperfect implementation using eval to create a function. Hope it sheds some light into the difference!
function makeFunction() {
var params = [];
for (var i = 0; i < arguments.length - 1; i++) {
params.push(arguments[i]);
}
var code = arguments[arguments.length - 1];
// Creates the anonymous function to be returned
// The following line doesn't work in IE
// return eval('(function (' + params.join(',')+ '){' + code + '})');
// This does though
return eval('[function (' + params.join(',')+ '){' + code + '}][0]');
}
The biggest difference between this and new Function is that Function is not lexically scoped. So it wouldn't have access to closure variables and mine would.