Skip to content

noThisInStatic

诊断类别:lint/complexity/noThisInStatic

¥Diagnostic Category: lint/complexity/noThisInStatic

自从:v1.3.1

¥Since: v1.3.1

来源:

¥Sources:

禁止在 static 上下文中使用 thissuper

¥Disallow this and super in static contexts.

在 JavaScript 中,静态上下文中的 this 关键字指的是类(构造函数)实例,而不是类的实例。这可能会让来自其他语言的开发者感到困惑,因为 this 通常指的是类的实例,而不是类本身。

¥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.

同样,静态上下文中的 super 指的是父类,而不是类的实例。如果没有正确理解,这可能会导致意外行为。

¥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.

此规则强制使用类名本身来访问静态方法,这可以使代码更清晰,更不容易出错。它有助于防止由于静态上下文中 thissuper 的独特行为而产生的误解和错误。

¥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

¥Invalid

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 }

¥Valid

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()
}
}

¥Related links