eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Disallow `super` and `this` in static methods
The this keyword on static methods refers the class instance (the constructor). This can be confusing.
Fail
class A {
static foo() {
doSomething()
}
static bar() {
this.foo() //ERROR: Unexpected 'this'.
}
}
class B extends A {
static foo() {
super.foo() //ERROR: Unexpected 'super'.
}
}
Pass
class A {
static foo() {
doSomething()
}
static bar() {
A.foo()
}
}
class B extends A {
static foo() {
A.foo()
}
}
Why is this confusing on a static method?
Well, it can be confusing to people switching between languages or are only used to languages where using this in a static context isn't allowed because it's reserved for class instances where here it's referring to the constructor.
It can also become imprecise when used with extended classes when a static this of a parent class no longer specifically refers to the parent class.
I would actually want the opposite, so I think the rule should let you enforce either this or "class name" in static methods. Same with super.
Any suggestions for the rule name?
Without "classname" how to access another property/method?
Without "classname" how to access another property/method?
Not sure I understand the question. I would access it with this or super.
Oh, sorry I misunderstood, I though this rule not allow this "class name" and super.
Something to consider.
When working in Typescript there are cases where you need to create or wrap things in anonymous classes. This is because you're passing down the generic type to the underlying static methods. More complex scenarios.
You may not have access to a class name. Not sure there's a likely default here.
With @sindresorhus on this as to enforcing either this or classname but this particular rule I can see being set per file in several cases.
Suggestions for the rule name:
this-and-super-in-static-methodsclass-reference-in-static-methods
Better suggestions welcome.
This is now accepted.
class-reference-in-static-methods
That seems to be the best and most concise for what this has turned into. The original proposal would probably have been something like no-static-this.
👍 for class-reference-in-static-methods
If anyone wants to work on this, see the initial attempt and feedback in https://github.com/sindresorhus/eslint-plugin-unicorn/pull/1119.