Index

no-new-func

禁止使用 Function 对象的 new 运算符

可以在运行时使用 Function 构造函数从字符串创建 JavaScript 函数,例如:

🌐 It’s possible to create functions in JavaScript from strings at runtime using the Function constructor, such as:

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() 及类似的方法从字符串创建代码。

🌐 This is considered by many to be a bad practice due to the difficulty in debugging and reading these types of functions. In addition, Content-Security-Policy (CSP) directives may disallow the use of eval() and similar methods for creating code from strings.

规则详情

🌐 Rule Details

此错误被提出是为了强调使用不良做法。通过将字符串传递给 Function 构造函数,你要求引擎解析该字符串,就像调用 eval 函数时必须解析字符串一样。

🌐 This error is raised to highlight the use of a bad practice. By passing a string to the Function constructor, you are requiring the engine to parse that string much in the way it has to when you call the eval function.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-new-func: "error"*/

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")();
const y = Function.bind(null, "a", "b", "return a + b"); // assuming that the result of Function.bind(...) will be eventually called.

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-new-func: "error"*/

const x = function (a, b) {
    return a + b;
};

选项

🌐 Options

此规则没有选项。

🌐 This rule has no options.

何时不使用

🌐 When Not To Use It

在更高级的情况下,当你确实需要使用 Function 构造函数时。

🌐 In more advanced cases where you really need to use the Function constructor.

版本

此规则是在 ESLint v0.0.7 中引入。

资源