ESLint prefer-arrow-callback错误

Sta*_*ouu 4 javascript ecmascript-6 eslint

我的ESLint有问题

这是我的功能:

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

以下是ESLint告诉我的内容:

warning  Missing function expression name  func-names
error    Unexpected function expression    prefer-arrow-callback
Run Code Online (Sandbox Code Playgroud)

如何解决这个错误?

Tus*_*har 5

它基本上是说在回调函数中使用箭头函数语法filter.

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

这是ESLINT文档prefer-arrow-callback所说的内容

箭头函数适用于回调,因为:

  • this 箭头函数中的关键字绑定到上部范围.

  • 箭头函数的表示法比函数表达式短.

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

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

foo(function(a) { return a; });
foo(function() { return this.a; }.bind(this));
Run Code Online (Sandbox Code Playgroud)

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

要解决错误,您可以

  1. 使用箭头函数语法(如上所示)
  2. 使用选项和命名函数来抑制错误

    /*eslint prefer-arrow-callback: ["error", { "allowNamedFunctions": true }]*/
    
    foo(function bar() {});
    
    Run Code Online (Sandbox Code Playgroud)