eslint/prefer-arrow-callback 样式
作用
要求回调使用箭头函数。
为什么这不好?
箭头函数通常更适合用于回调,因为它们:
- 从外围作用域继承
this,避免了常见的错误来源; - 更简短,也更易于阅读;
- 不能用作构造函数,这一点对回调来说是理想的。
示例
以下是此规则的错误代码示例:
js
foo(function (a) {
return a;
});
foo(
function () {
return this.a;
}.bind(this),
);以下是此规则的正确代码示例:
js
foo((a) => a);
foo(function* () {
yield;
});
foo(function () {
this;
});
foo(function bar() {
bar();
});配置
allowNamedFunctions
type: boolean
default: false
如果将此选项设置为 true,则允许命名函数表达式。
allowUnboundThis
type: boolean
default: true
如果将此选项设置为 false,即使函数表达式未绑定到 this 值,引用了 this 的函数表达式也会被报告。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"prefer-arrow-callback": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"prefer-arrow-callback": "error",
},
});bash
oxlint --deny prefer-arrow-callback版本
此规则于 v1.65.0 中添加。
