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

后端 未结 6 1848
北海茫月
北海茫月 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:53

    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.

提交回复
热议问题