javascript - 函数构造函数与 eval

标签 javascript function

我在 MDN docs 上偶然发现了这一点关于函数

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues to eval. However, unlike eval, the Function constructor creates functions which execute in the global scope only.

有人可以解释一下什么是函数构造函数以及什么是 eval 吗?或者换句话说,有人可以提前向我解释一下上述说法吗?

最佳答案

这本质上意味着 new Function('...')eval('...') 以类似的方式工作,从某种意义上说,它们会将参数中的字符串计算为 JS 表达式。但是,它们有不同的范围规则:

  • new Function() 只能访问全局范围
  • eval() 可以访问本地范围

一个例子是这样的:

  • 您创建一个函数,例如 f,即 new Function('console.log(x)'),然后调用它。无论调用哪个作用域 f(),它都会始终在全局作用域上记录 x 的值
  • 您有eval('console.log(x)')x 的值取决于 eval() 所在的范围:

const x = 'global x';
const f = new Function('console.log(x)');

f(); // logs 'global x'
eval('console.log(x)'); // logs 'global x'

// Let's create a function scope
function test() {
  const x = 'local x';
  const f = new Function('console.log(x)');

  f(); // logs 'global x'
  eval('console.log(x)'); // logs 'local x';
}
test();

关于javascript - 函数构造函数与 eval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60919433/

相关文章:

python - 类和函数范围

javascript - useState 与 React 中的异步操作冲突

string - Excel 函数格式

javascript - jQuery/Javascript 获取多个元素的类以显示具有该类的元素

javascript - TestCafe requestHook 响应正文未提供文本

c - switch 和 case 语句中的错误

python - 无需调用即可检查 python 函数签名

c++ - C++中的默认参数有一些特殊的属性吗?

javascript - 基于字节而不是字符计数的 Substr

javascript - 设置单选按钮在单击文本区域时选中