eval() 和 new Function() 是一回事吗? [英] Are eval() and new Function() the same thing?

查看:36
本文介绍了eval() 和 new Function() 是一回事吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个函数在幕后做同样的事情吗?(在单语句函数中)

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'));

推荐答案

不,它们相同.

  • eval() 将字符串计算为当前执行范围内的 JavaScript 表达式,并且可以访问局部变量.
  • new Function() 将存储在字符串中的 JavaScript 代码解析为函数对象,然后可以调用该函数对象.它无法访问局部变量,因为代码在单独的范围内运行.
  • 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.

考虑这个代码:

function test1() {
    var a = 11;
    eval('(a = 22)');
    alert(a);            // alerts 22
}

如果使用 new Function('return (a = 22);')(),局部变量 a 将保留其值.尽管如此,Douglas Crockford 等一些 JavaScript 程序员认为 两者都不应该使用 除非绝对必要,并且评估/使用不可信数据上的函数构造函数是不安全和不明智的.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆