ESLint prefer-arrow-callback 错误

ESLint prefer-arrow-callback error

我遇到了 ESLint 的问题

这是我的函数:

$productItem.filter(function (i, el) {
        return el.getBoundingClientRect().top < evt.clientY
    }).last()
    .after($productItemFull)

这是 ESLint 告诉我的:

warning  Missing function expression name  func-names
error    Unexpected function expression    prefer-arrow-callback

如何解决这个错误?

基本上就是说在filter回调函数中使用Arrow function语法。

$productItem.filter((i, el) => el.getBoundingClientRect().top < evt.clientY)
    //              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    .last()
    .after($productItemFull);

这是ESLINT documentation for prefer-arrow-callback所说的

Arrow functions are suited to callbacks, because:

  • this keywords in arrow functions bind to the upper scope’s.

  • The notation of the arrow function is shorter than function expression’s.

并且,在以下情况下会抛出错误

/*eslint prefer-arrow-callback: "error"*/

foo(function(a) { return a; });
foo(function() { return this.a; }.bind(this));

您的代码与第一个代码段相同。因此,错误 prefer-arrow-callback 由 ESLint 显示。

要解决错误,您可以

  1. 使用Arrow function语法(如上所示)

  2. 使用 options 和命名函数

    抑制错误
    /*eslint prefer-arrow-callback: ["error", { "allowNamedFunctions": true }]*/
    
    foo(function bar() {});
    

解决 eslint 中的“unexpected function expression. (prefer-allow-callback)”错误 在代码开头写这段代码:

/*eslint prefer-arrow-callback: 0*/