Exploring the Difference Between eval() and new Function()
In JavaScript, eval() and new Function() are often compared to understand their similarities and differences. This article examines whether they perform the same task and provides a detailed explanation of their distinct behaviors.
Code Examples
Consider the following code snippet:
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'));
In this code, evaluate() uses eval() to evaluate a string as a JavaScript expression, while func() uses the new Function() constructor to create a function object from a string and immediately executes it.
Distinct Functionality
While both functions evaluate strings, they do not perform the same task. Here are the key differences:
eval():
new Function():
Example to Highlight Differences
Consider the following code:
function test1() { var a = 11; eval('(a = 22)'); alert(a); // alerts 22 }
If new Function('return (a = 22);')() were used instead of eval(), the local variable a would retain its original value because new Function() does not access local variables from the surrounding scope.
Recommendations and Security Considerations
Some JavaScript developers, such as Douglas Crockford, advocate against using eval() and new Function() unless absolutely necessary. This recommendation stems from security concerns, as evaluating untrusted data with either function can be risky.
Therefore, it is generally advisable to explore alternative methods for evaluating and executing JavaScript code before resorting to eval() or new Function().
The above is the detailed content of Eval() vs. New Function(): Do They Really Do the Same Thing?. For more information, please follow other related articles on the PHP Chinese website!