Skip to content
← Back to rules

eslint/no-new-func Style

作用

该规则禁止对 Function 对象使用 new 运算符。

为什么这不好?

使用 new FunctionFunction 会导致代码难以理解和维护。它可能带来与 eval 类似的安全风险,因为它会从字符串代码生成一个新函数,这可能成为注入攻击的载体。此外,这些函数不会被 JavaScript 引擎优化,因此会对性能产生负面影响。

示例

以下是此规则的错误代码示例:

js
var x = new Function("a", "b", "return a + b");
var x = Function("a", "b", "return a + b");
var x = Function.call(null, "a", "b", "return a + b");
var x = Function.apply(null, ["a", "b", "return a + b"]);
var x = Function.bind(null, "a", "b", "return a + b")();
var f = Function.bind(null, "a", "b", "return a + b");

以下是此规则的正确代码示例:

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

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "no-new-func": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "no-new-func": "error",
  },
});
bash
oxlint --deny no-new-func

版本

此规则于 v0.9.2 中添加。

参考资料