コンテンツにスキップ

noThisInStatic

このコンテンツはまだ日本語訳がありません。

Diagnostic Category: lint/complexity/noThisInStatic

Since: v1.3.1

Sources:

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.

class A {
static CONSTANT = 0;
static foo() {
this.CONSTANT;
}
}
code-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 }

class B extends A {
static bar() {
super.CONSTANT;
}
}
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 }

class B extends A {
static ANOTHER_CONSTANT = A.CONSTANT + 1;
static foo() {
A.CONSTANT;
B.ANOTHER_CONSTANT;
}
bar() {
this.property;
}
}
class A {
static foo() {
doSomething()
}
bar() {
A.foo()
}
}