The difference between eval and new Function

eval and new Function can be dynamically parsed and executed string. But they differ on the analytical determination of the content of the operating environment.

var a = 'global scope'
      function b(){
           var a = 'local scope'
           eval('console.log(a)') //local scope
           ;(new Function('','console.log(a)'))() //global scope
      }
      b()
复制代码

Scope eval code when execution of the current scope. It can access the local variables.

When the scope of the new Function code execution as the global scope, regardless of the place in which it is invoked. So it is accessible to a global variable a. It simply can not access the local variables within the function b.

Note that when we do not define a variable b in the function, the same output of the two methods. This does not conflict with the above conclusion. Because when the code is executed, the variable is to look from the inside out. When the eval code execution, it remains a priority to find a variable from inside the b function, when looking less, to find a global, this time to find a course 'global scope'

var a = 'global scope'
        function b(){
            //var a = 'local scope' 
            eval('console.log(a)') //global scope
            ;(new Function('','console.log(a)'))() //global scope
        }
        b()
复制代码
function sayHi(sName, sMessage) {
  alert("Hello " + sName + sMessage);
}
函数生命可以写成这样的形式
所以也就很容易理解 new Function()可以执行js代码了,并且,只能执行全局的
var sayHi = new Function("sName", "sMessage", "alert(\"Hello \" + sName + sMessage);");
复制代码

Note: Although you can create a function using the Function constructor, but it is best not to use it because it is defined by function than the traditional way is much slower. However, all functions should be considered as examples of the Function class.

    var arr = [];
    var obj = {}
    console.log(Object.prototype.toString.call(arr));  //[object Array]
    console.log(Object.prototype.toString.call(obj));   //[object Object]s
复制代码

Guess you like

Origin blog.csdn.net/weixin_33713350/article/details/91384903