eslint/class-methods-use-this 限制
它的作用
强制要求类方法使用 this。
为什么这是个问题?
对于不使用 this 的类方法,你应该考虑将其转换为 static 方法。虽然这并不总是可行或可取,但这样有助于明确该方法不依赖于实例状态。
如果你确实将方法转换为 static 函数,则调用该方法的类实例也必须相应地改为静态调用。
示例
此规则的 错误 代码示例:
js
class A {
foo() {
console.log("Hello World");
}
}此规则的 正确 代码示例:
js
class A {
foo() {
this.bar = "Hello World"; // 正确,此处使用了 this
}
}
class B {
constructor() {
// 正确。constructor 被豁免
}
}
class C {
static foo() {
// 正确。静态方法不要求使用 this。
}
}配置
此规则接受一个配置对象,包含以下属性:
enforceForClassFields
type: boolean
default: true
对作为函数的类字段强制应用此规则。
exceptMethods
type: array
default: []
要从此规则中豁免的方法名称列表。
exceptMethods[n]
type: object
exceptMethods[n].name
type: string
exceptMethods[n].private
type: boolean
ignoreClassesWithImplements
type: "all" | "public-fields"
default: null
是否忽略实现接口的类。
ignoreOverrideMethods
type: boolean
default: false
是否忽略被重写的成员方法。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"class-methods-use-this": "error"
}
}bash
oxlint --deny class-methods-use-this