Javascript eval() 和 new Function() 是一回事吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4599857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are eval() and new Function() the same thing?
提问by qwertymk
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'));
回答by PleaseStand
No, they are notthe 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.
eval()
将字符串计算为当前执行范围内的 JavaScript 表达式,并且可以访问局部变量。new Function()
将存储在字符串中的 JavaScript 代码解析为一个函数对象,然后可以调用该函数对象。它无法访问局部变量,因为代码在单独的范围内运行。
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 usedunless absolutely necessary, and evaling/using the Function
constructor on untrusted data is insecure and unwise.
如果new Function('return (a = 22);')()
使用,局部变量a
将保留其值。尽管如此,Douglas Crockford 等一些 JavaScript 程序员认为,除非绝对必要,否则不应使用两者,并且对不可信数据进行评估/使用构造函数是不安全和不明智的。Function
回答by palswim
No.
不。
In your update, the calls to evaluate
and func
produce the same result. But, they are most definitely not "doing the same thing behind the scenes". The func
function creates a new function, but then immediately executes it, whereas the evaluate
function simply executes the code on the spot.
在您的更新中,调用evaluate
和func
产生相同的结果。但是,他们绝对不是“在幕后做同样的事情”。该func
函数创建一个新函数,然后立即执行它,而该evaluate
函数只是在现场执行代码。
From the original question:
从原来的问题:
var evaluate = function(string) {
return eval(string);
}
var func = function(string) {
return (new Function( 'return (' + string + ')' )());
}
These will give you very different results:
这些会给你非常不同的结果:
evaluate('0) + (4');
func('0) + (4');
回答by Juan Mendes
new Function
creates a function that can be reused. eval
just executes the given string and returns the result of the last statement. Your question is misguided as you attempted to create a wrapper function that uses Function to emulate an eval.
new Function
创建一个可以重用的函数。eval
只执行给定的字符串并返回最后一条语句的结果。当您试图创建一个使用 Function 来模拟 eval 的包装函数时,您的问题被误导了。
Is it true that they share some code behind the curtains? Yes, very likely. Exactly the same code? No, certainly.
他们在幕后共享一些代码是真的吗?是的,很有可能。完全一样的代码?不,当然。
For fun, here's my own imperfect implementation using eval to create a function. Hope it sheds some light into the difference!
为了好玩,这是我自己使用 eval 创建函数的不完美实现。希望它能揭示一些差异!
function makeFunction() {
var params = [];
for (var i = 0; i < arguments.length - 1; i++) {
params.push(arguments[i]);
}
var code = arguments[arguments.length - 1];
// Creates the anonymous function to be returned
// The following line doesn't work in IE
// return eval('(function (' + params.join(',')+ '){' + code + '})');
// This does though
return eval('[function (' + params.join(',')+ '){' + code + '}][0]');
}
The biggest difference between this and new Function is that Function is not lexically scoped. So it wouldn't have access to closure variables and mine would.
this 和 new Function 的最大区别在于 Function 没有词法作用域。所以它不能访问闭包变量,而我的可以。
回答by Hyman D Menendez
Just want to point out some syntax used in the examples here and what it means:
只想指出这里示例中使用的一些语法及其含义:
var func = function(string) {
return (new Function( 'return (' + string + ')' )());
}
notice that the Function(...)() has the "()" at the end. This syntax will cause func to execute the new function and return the string not a function that returns string, but if you use the following:
请注意,Function(...)() 末尾有“()”。此语法将导致 func 执行新函数并返回字符串而不是返回字符串的函数,但如果您使用以下内容:
var func = function(string) {
return (new Function( 'return (' + string + ')' ));
}
Now func will return a function that returns a string.
现在 func 将返回一个返回字符串的函数。
回答by Timothy Khouri
If you mean, will it yield the same results, then yes... but just to eval (aka, "evaluate this string of JavaScript") would be much simpler.
如果你的意思是,它会产生相同的结果,那么是的……但只是 eval(也就是“评估这个 JavaScript 字符串”)会简单得多。
EDIT Below:
编辑下面:
It's like saying... are these two math problems the same:
这就像在说……这两个数学问题是一样的吗:
1 + 1
1 + 1
1 + 1 + 1 - 1 + 1 - 1 * 1 / 1
1 + 1 + 1 - 1 + 1 - 1 * 1 / 1
回答by Chris Laplante
In that example, the results are the same, yes. Both execute the expression you pass. This is what makes them so dangerous.
在那个例子中,结果是一样的,是的。两者都执行您传递的表达式。这就是让他们如此危险的原因。
But they do different things behind the scense. The one involving new Function()
, behind-the-scenes, creates an anonymous function from the code you supply, which is executed when the function is invoked.
但他们在幕后做不同的事情。涉及new Function()
幕后的那个,根据您提供的代码创建一个匿名函数,该函数在调用该函数时执行。
The JavaScript you pass to it is technically not executed until you invoke the anonymous function. This is in contrast to eval()
which executes the code right away, and doesn't generate a function based on it.
您传递给它的 JavaScript 从技术上讲在您调用匿名函数之前不会执行。这与立即eval()
执行代码并且不基于它生成函数形成对比。