【问题标题】:ESLint prefer-arrow-callback errorESLint 首选箭头回调错误
【发布时间】:2016-11-08 08:56:24
【问题描述】:

我遇到了 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

如何解决这个错误?

【问题讨论】:

    标签: javascript ecmascript-6 eslint


    【解决方案1】:

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

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

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

    箭头函数适合回调,因为:

    • 箭头函数中的this关键字绑定到上层作用域。

    • 箭头函数的符号比函数表达式短。

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

    /*eslint prefer-arrow-callback: "error"*/
    
    foo(function(a) { return a; });
    foo(function() { return this.a; }.bind(this));
    

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

    要解决这个错误,你可以

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

    2. 使用options 和命名函数抑制错误

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        • 2018-07-24
        • 2017-09-13
        • 2020-07-30
        • 1970-01-01
        相关资源
        最近更新 更多