noThisInStatic
Diagnostic Category: lint/complexity/noThisInStatic
Since: v1.3.1
Sources:
- Same as:
@mysticatea/no-this-in-static
Disallow this
and super
in static
contexts.
In JavaScript, the this
keyword in static contexts refers to the class (the constructor) instance,
not an instance of the class. This can be confusing for developers coming from other languages where
this
typically refers to an instance of the class, not the class itself.
Similarly, super
in static contexts refers to the parent class, not an instance of the class.
This can lead to unexpected behavior if not properly understood.
This rule enforces the use of the class name itself to access static methods,
which can make the code clearer and less prone to errors. It helps to prevent
misunderstandings and bugs that can arise from the unique behavior of this
and super
in static contexts.
Example
Section titled ExampleInvalid
Section titled Invalidcode-block.js:5:9 lint/complexity/noThisInStatic FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Using this in a static context can be confusing.
4 │ static foo() {
> 5 │ this.CONSTANT;
│ ^^^^
6 │ }
7 │ }
ℹ this refers to the class.
ℹ Unsafe fix: Use the class name instead.
3 3 │
4 4 │ static foo() {
5 │ - ········this.CONSTANT;
5 │ + ········A.CONSTANT;
6 6 │ }
7 7 │ }
code-block.js:3:9 lint/complexity/noThisInStatic FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Using super in a static context can be confusing.
1 │ class B extends A {
2 │ static bar() {
> 3 │ super.CONSTANT;
│ ^^^^^
4 │ }
5 │ }
ℹ super refers to a parent class.
ℹ Unsafe fix: Use the class name instead.
1 1 │ class B extends A {
2 2 │ static bar() {
3 │ - ········super.CONSTANT;
3 │ + ········A.CONSTANT;
4 4 │ }
5 5 │ }