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

后端 未结 6 1783
北海茫月
北海茫月 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 12:05

    No.

    In your update, the calls to evaluate and func produce the same result. But, they are most definitely not "doing the same thing behind the scenes". The func function creates a new function, but then immediately executes it, whereas the evaluate function simply executes the code on the spot.

    From the original question:

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

    These will give you very different results:

    evaluate('0) + (4');
    func('0) + (4');
    

提交回复
热议问题