Eval and new funciton not the same thing |
1、函数声明式 复制代码 代码如下: function foo(){ //code } 在JS中,函数也是对象,函数对象连接到Function.prototype( Function.prototype连接到Object.prototype) 2、函数字面量式 复制代码 代码如下: var foo = function foo(){ //code } 对象拥有一个连到原型对象的隐藏连接 。对象字面量间生的对象连接到Object.prototype 。 foo.__proto__ == Function.prototype 3、使用New的构造函数生成 new Function ([arg1[, arg2[, ... argN]],] functionBody); 每次执行都生成新的函数 网上的资料有很多介绍这三种模式的,前2种几乎是相同的,基于相同的词法作用域 。 词法作用域:变量的作用域是在定义时决定而不是执行时决定,也就是说词法作用域取决于源码,通过静态分析就能确定,因此词法作用域也叫做静态作用域 。 with和eval除外,所以只能说JS的作用域机制非常接近词法作用域(Lexical scope) 。 突然感觉有点离题了,这篇文章其实是记录eval和New Function的区别,下面回归正题: 以前有人会说,new Function的方式是几乎与eval相等,今天我查了一下,确实是不同的东西,说这句话的人太不负责了 。关于eval和new function,得到的结果都是一致的,都会叫你不要去使用它们 。所以结论就是“不得不”才使用 。 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. 从以上2点看出,eval的作用域是现行的作用域,而new Function是动态生成的,它的作用域始终都是window 。并且,eval可以读到本地的变量,new Function则不能 。 复制代码 代码如下: function test() { var a = 11; eval((a = 22)); //如果是new Function(return (a = 22);)(); a的值是不会覆盖的 。 alert(a); // alerts 22 } 所以一般eval只用于转换JSON对象,new Function也有特殊的用途,只是在不清楚的情况下还是少用为妙 。 更多资料:邪恶的eval和new Function 这里作个备份: 代码: 复制代码 代码如下: // 友善提醒:为了你的手指安全,请在Chrome下运行 alert("hello").replace(/.+/, eval); alert("hello").replace(/.+/, function(m){new Function(m)();}); var i = 0; eval(new Array(101).join(alert(++i);)); var i = 0; new Function(new Array(101).join(alert(++i);))(); |