no-new-func
禁用带有 Function
对象的 new
操作符
在 JavaScript 中,可以在运行时使用 Function
构造函数从字符串创建函数,例如
const a = new Function("a", "b", "return a + b");
const b = Function("a", "b", "return a + b");
const c = Function.call(null, "a", "b", "return a + b");
const d = Function.apply(null, ["a", "b", "return a + b"]);
const x = Function.bind(null, "a", "b", "return a + b")();
由于调试和阅读这些类型的函数存在困难,许多人认为这是一种不良实践。 此外,内容安全策略 (CSP) 指令可能禁止使用 eval()
和类似方法从字符串创建代码。
规则详情
引发此错误是为了强调不良实践的使用。 通过将字符串传递给 Function
构造函数,您需要引擎解析该字符串,这与调用 eval
函数时的情况非常相似。
此规则的 错误 代码示例
在在线演练场中打开
/*eslint no-new-func: "error"*/
const a = ;
const b = ;
const c = ;
const d = ;
const x = ();
const y = ; // assuming that the result of Function.bind(...) will be eventually called.
此规则的 正确 代码示例
在在线演练场中打开
/*eslint no-new-func: "error"*/
const x = function (a, b) {
return a + b;
};
何时不使用
在更高级的情况下,您确实需要使用 Function
构造函数。
版本
此规则在 ESLint v0.0.7 中引入。