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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…