eval()和new Function()是一样的吗? [英] Are eval() and new Function() the same thing?
问题描述
这两个功能是在幕后做同样的事情吗? (在单个语句函数中)
$ b $ pre $ $ $ $ c $ var evaluate = function(string){
return eval('('+ string +')');
var func = function(string){
return(new Function('return('+ string +')')());
}
console.log(evaluate('2 + 1'));
console.log(func('2 + 1'));
不,不是相同。
-
eval()
将字符串评估为JavaScript表达式当前的执行范围,并且可以访问局部变量。
-
new Function()
将存储在字符串中的JavaScript代码解析为函数对象,然后可以调用它。它不能访问局部变量,因为代码运行在一个单独的作用域中。
请考虑以下代码:
function test1(){
var a = 11;
eval('(a = 22)');
警报(a); // alert 22
如果 new Function('return (a = 22);')()
被使用,局部变量 a
会保留它的值。尽管如此,一些JavaScript程序员,例如Douglas Crockford认为不应该被使用除非绝对必要,以及评估/使用函数
对不可信数据的构造函数是不安全的,也是不明智的。
Are these two functions doing the same thing behind the scenes? (in single statement functions)
var evaluate = function(string) {
return eval('(' + string + ')');
}
var func = function(string) {
return (new Function( 'return (' + string + ')' )());
}
console.log(evaluate('2 + 1'));
console.log(func('2 + 1'));
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.
这篇关于eval()和new Function()是一样的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!