Are eval() and new Function() the same thing?

后端 未结 6 1885
北海茫月
北海茫月 2020-11-22 11:25

Are these two functions doing the same thing behind the scenes? (in single statement functions)

var evaluate = function(string) {
    return eval(\'(\' + str         


        
6条回答
  •  忘掉有多难
    2020-11-22 11:54

    Just want to point out some syntax used in the examples here and what it means:

     var func = function(string) {
         return (new Function( 'return (' + string + ')' )());
     }
    

    notice that the Function(...)() has the "()" at the end. This syntax will cause func to execute the new function and return the string not a function that returns string, but if you use the following:

     var func = function(string) {
         return (new Function( 'return (' + string + ')' ));
     }
    

    Now func will return a function that returns a string.

提交回复
热议问题