eslint/prefer-arrow-callback 样式
作用
要求回调使用箭头函数。
为什么这不好?
箭头函数通常更适合用于回调,因为它们:
- 从外围作用域继承
this,避免了常见的错误来源; - 更简短,也更易于阅读;
- 不能用作构造函数,这一点对回调来说是理想的。
选项
json
{
"prefer-arrow-callback": [
"error",
{
"allowNamedFunctions": false,
"allowUnboundThis": true
}
]
}allowNamedFunctions(默认false)— 当为true时,允许命名函数 表达式。allowUnboundThis(默认true)— 当为false时,引用this的函数 表达式即使未绑定到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
allowUnboundThis
type: boolean
default: true
如何使用
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 中添加。
