jQuery使用(new Function(" return" + data))();而不是eval(数据);解析JSON,为什么? [英] jQuery uses (new Function("return " + data))(); instead of eval(data); to parse JSON, why?
问题描述
此链接向您显示jQuery使用(新功能(对旧版浏览器返回+ data))();
,解析JSON字符串而不是 eval()
。
This link shows you that jQuery uses (new Function("return " + data))();
for older browsers, to parse a JSON string instead of eval()
.
这有什么好处?如果JSON字符串不是安全怎么办?
What are the benefits of this? What if the JSON string isn't safe?
推荐答案
尼克答案中的引用暗示了它。这并不是一个很大的区别,但感觉 eval
比新功能
更糟糕。不是在安全性方面 - 面对不受信任的输入,它们同样无用,但希望你的webapp不会返回不受信任的JSON字符串 - 但是在语言级别的怪异方面,因此对优化的抵制。
The quote in Nick's answer hints at it. It's not really a big difference, but the feeling is that eval
is ‘worse’ than new Function
. Not in terms of security — they're both equally useless in the face of untrusted input, but then hopefully your webapp is not returning untrusted JSON strings — but in terms of language-level weirdness, and hence resistance to optimisation.
具体来说:
function victim() {
var a= 1;
eval('a= 2');
return a;
}
给出 2
。 eval
ed字符串已在受害者
的本地变量范围内运行!这是常规用户编写的功能永远不会做的事情; eval
只能这样做,因为它是黑魔法。
gives 2
. The eval
ed string has operated on victim
's local variable scope! This is something that a regular user-written function could never do; eval
can only do it because it is dark magic.
使用常规函数取而代之的是魔法元素:
Using a regular function instead takes away this element of magic:
function victim() {
var a= 1;
(new Function('a= 2;'))();
return a;
}
在上面,返回 a
仍然 1
;新函数只能在自己的局部变量或全局 window.a
上运行。
in the above, the returned a
remains 1
; the new Function can only operate on its own local variables or the global window.a
.
该知识允许代码分析工具 - 可能包括JavaScript引擎,特别是聪明的minifiers - 以应用更多优化。例如,第二个受害者
函数可以将 a
变量完全优化到返回1
。使用 eval
并进行大量潜在的优化是不可行的。
That knowledge allows code analysis tools — which might include JavaScript engines and particularly clever minifiers — to apply more optimisations. For example the second victim
function could have the a
variable completely optimised away to return 1
. One use of eval
and a lot of potential optimisations aren't going to be doable.
当然在实践中对于像JSON eval
这样的小函数,没有明显的区别,但一般来说,思路是:
Of course in practice for a tiny function like a JSON eval
er, there isn't going to be a noticeable difference, but in general the thinking is:
- 尽可能避免两种方法(在ECMAScript第五版的严格模式中都不允许使用它们);
- 如果你必须使用一种,
new Function
优于eval
,除非你真的需要代码来访问调用函数的局部变量。
- avoid both approaches wherever possible (they are both disallowed in ECMAScript Fifth Edition's Strict Mode);
- if you have to use one,
new Function
is preferable toeval
, unless you really need the code to access the calling function's local variables.
这篇关于jQuery使用(new Function(" return" + data))();而不是eval(数据);解析JSON,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!