版本

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 中引入。

延伸閱讀

資源

變更語言