Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  22] [ 7]  / answers: 1 / hits: 62996  / 14 Years ago, wed, january 5, 2011, 12:00:00

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'));

More From » function

 Answers
33

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.


[#94376] Monday, January 3, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
francokeganr

Total Points: 438
Total Questions: 102
Total Answers: 124

Location: Belarus
Member since Sat, Jul 18, 2020
4 Years ago
;