欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Eval and new funciton not the same thing

 更新時(shí)間:2012年12月27日 15:32:22   投稿:mdxy-dxy  
以前有人會(huì)說(shuō),new Function的方式是幾乎與eval相等,今天我查了一下,確實(shí)是不同的東西,說(shuō)這句話的人太不負(fù)責(zé)了。關(guān)于eval和new function,得到的結(jié)果都是一致的,都會(huì)叫你不要去使用它們。所以結(jié)論就是“不得不”才使用

1、函數(shù)聲明式

復(fù)制代碼 代碼如下:

function foo(){
//code
}

在JS中,函數(shù)也是對(duì)象,函數(shù)對(duì)象連接到Function.prototype( Function.prototype連接到Object.prototype)
2、函數(shù)字面量式
復(fù)制代碼 代碼如下:

var foo = function foo(){
//code
}

對(duì)象擁有一個(gè)連到原型對(duì)象的隱藏連接。對(duì)象字面量間生的對(duì)象連接到Object.prototype。 foo.__proto__ == Function.prototype
3、使用New的構(gòu)造函數(shù)生成

new Function ([arg1[, arg2[, ... argN]],] functionBody);

每次執(zhí)行都生成新的函數(shù)
網(wǎng)上的資料有很多介紹這三種模式的,前2種幾乎是相同的,基于相同的詞法作用域。

詞法作用域:變量的作用域是在定義時(shí)決定而不是執(zhí)行時(shí)決定,也就是說(shuō)詞法作用域取決于源碼,通過(guò)靜態(tài)分析就能確定,因此詞法作用域也叫做靜態(tài)作用域。 with和eval除外,所以只能說(shuō)JS的作用域機(jī)制非常接近詞法作用域(Lexical scope)。
突然感覺(jué)有點(diǎn)離題了,這篇文章其實(shí)是記錄eval和New Function的區(qū)別,下面回歸正題:

以前有人會(huì)說(shuō),new Function的方式是幾乎與eval相等,今天我查了一下,確實(shí)是不同的東西,說(shuō)這句話的人太不負(fù)責(zé)了。關(guān)于eval和new function,得到的結(jié)果都是一致的,都會(huì)叫你不要去使用它們。所以結(jié)論就是“不得不”才使用。

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點(diǎn)看出,eval的作用域是現(xiàn)行的作用域,而new Function是動(dòng)態(tài)生成的,它的作用域始終都是window。并且,eval可以讀到本地的變量,new Function則不能。
復(fù)制代碼 代碼如下:

function test() {
var a = 11;
eval('(a = 22)'); //如果是new Function('return (a = 22);')(); a的值是不會(huì)覆蓋的。
alert(a); // alerts 22
}

所以一般eval只用于轉(zhuǎn)換JSON對(duì)象,new Function也有特殊的用途,只是在不清楚的情況下還是少用為妙。

這里作個(gè)備份:

代碼:
復(fù)制代碼 代碼如下:

// 友善提醒:為了你的手指安全,請(qǐng)?jiān)贑hrome下運(yùn)行
'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);'))();

相關(guān)文章

最新評(píng)論