版本

no-eval

禁用 eval() 的使用

JavaScript 的 eval() 函数具有潜在危险,并且经常被误用。在不可信的代码上使用 eval() 可能会使程序容易受到多种不同的注入攻击。在大多数情况下,可以使用更好、更替代的方法来代替使用 eval()

const obj = { x: "foo" },
    key = "x",
    value = eval("obj." + key);

规则详情

此规则旨在通过禁用 eval() 函数的使用来防止潜在的危险、不必要的和缓慢的代码。因此,每当使用 eval() 函数时,它都会发出警告。

此规则的不正确代码示例

在 Playground 中打开
/*eslint no-eval: "error"*/

const obj = { x: "foo" },
    key = "x",
    value = eval("obj." + key);

(0, eval)("const a = 0");

const foo = eval;
foo("const a = 0");

// This `this` is the global object.
this.eval("const a = 0");

使用 window 全局变量的此规则的附加不正确代码示例

在 Playground 中打开
/*eslint no-eval: "error"*/
/*global window*/

window.eval("const a = 0");

使用 global 全局变量的此规则的附加不正确代码示例

在 Playground 中打开
/*eslint no-eval: "error"*/
/*global global*/

global.eval("const a = 0");

此规则的正确代码示例

在 Playground 中打开
/*eslint no-eval: "error"*/

const obj = { x: "foo" },
    key = "x",
    value = obj[key];

class A {
    foo() {
        // This is a user-defined method.
        this.eval("const a = 0");
    }

    eval() {
    }

    static {
        // This is a user-defined static method.
        this.eval("const a = 0");
    }

    static eval() {
    }
}

选项

allowIndirect

此规则有一个选项来允许“间接 eval”。间接调用 eval 的危险性低于直接调用 eval,因为它们不能动态更改作用域。因此,它们也不会像直接 eval 那样对性能产生负面影响。

{
    "no-eval": ["error", {"allowIndirect": true}] // default is false
}

使用 {"allowIndirect": true} 选项的此规则的不正确代码示例

在 Playground 中打开
/*eslint no-eval: ["error", {"allowIndirect": true} ]*/

const obj = { x: "foo" },
    key = "x",
    value = eval("obj." + key);

使用 {"allowIndirect": true} 选项的此规则的正确代码示例

在 Playground 中打开
/*eslint no-eval: ["error", {"allowIndirect": true} ]*/

(0, eval)("const a = 0");

const foo = eval;
foo("const a = 0");

this.eval("const a = 0");
在 Playground 中打开
/*eslint no-eval: ["error", {"allowIndirect": true} ]*/
/*global window*/

window.eval("const a = 0");
在 Playground 中打开
/*eslint no-eval: ["error", {"allowIndirect": true} ]*/
/*global global*/

global.eval("const a = 0");

已知限制

  • 即使 eval 不是全局的,此规则也会警告每个 eval()。此行为是为了检测直接 eval 的调用。例如

    module.exports = function(eval) {
        // If the value of this `eval` is built-in `eval` function, this is a
        // call of direct `eval`.
        eval("const a = 0");
    };
    
  • 此规则无法捕获重命名全局对象的情况。例如

    const foo = window;
    foo.eval("const a = 0");
    

版本

此规则在 ESLint v0.0.2 中引入。

延伸阅读

资源

更改语言