What is the difference between new Function
and eval
, since both seem to do the same thing?
Example with eval
:
eval('1 + 1'); // 2
Example with new Function
:
new Function('', 'return (1+1)')() // 2
What is the difference between new Function
and eval
, since both seem to do the same thing?
Example with eval
:
eval('1 + 1'); // 2
Example with new Function
:
new Function('', 'return (1+1)')() // 2
The eval () method evaluates JavaScript code represented as a string. MDN
The Function constructor creates a new Function object. In JavaScript every function is actually a Function object. - MDN
Free translation:
The
Function
constructor creates a new anonymous function object. In Javascript all functions are currently a function object.
Documentation self-explanates, basically eval executes an expression, statement , and so on. The Function constructor creates a new function object entitled to all its prototype .
var a = new Function('', 'return (1+1)');
var b = eval("2 + a()");
var c = b + a();
var d = new Function("p", "return a() + b + c + p");
var e = eval("d(10) - 20");
console.log(a()) // 2
console.log(b) // 4
console.log(c) // 6
console.log(d(10)) // 22
console.log(e); // 2
On the W3Schools site has this example in the Function
constructor session:
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
And then say the following followed by another example:
You actually do not have to use the constructor function. The above above is the same as writing:
var myFunction = function (a, b) {return a * b}; var x = myFunction(4, 3);
The phrase reads as follows (free translation):
You do not currently need to use the function constructor. The example below has the same effect.
They do not do the same thing:
eval()
evaluates a string as a JavaScript expression within the current scope and can access local variables.
new Function
parse the code for a function object, which can be called. It can not access local variables because the code runs in a separate scope.
What does this mean? Run this code:
function testEval() {
var a = 'original';
eval("(a = 'alterado')");
console.log(a);
}
function testNewFunction() {
var a = 'original';
new Function("(a = 'alterado')")();
console.log(a);
}
When we use eval
the value of the variable a
is changed. When we use new Function
it remains unchanged.