noThisInStatic
¥Summary
-
规则生效日期:
v1.3.1¥Rule available since:
v1.3.1 -
诊断类别:
lint/complexity/noThisInStatic¥Diagnostic Category:
lint/complexity/noThisInStatic -
此规则为推荐规则,默认启用。
¥This rule is recommended, which means is enabled by default.
-
此规则包含 safe 修复程序。
¥This rule has a safe fix.
-
此规则的默认严重级别为 warning。
¥The default severity of this rule is warning.
-
来源:
¥Sources:
-
与
@mysticatea/no-this-in-static相同¥Same as
@mysticatea/no-this-in-static
-
¥How to configure
{ "linter": { "rules": { "complexity": { "noThisInStatic": "error" } } }}¥Description
禁止在 static 上下文中使用 this 和 super。
¥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.
此规则强制使用类名本身来访问静态方法,这可以使代码更清晰,更不容易出错。它有助于防止由于静态上下文中 this 和 super 的独特行为而产生的误解和错误。
¥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.
ℹ Safe 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.
ℹ Safe 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
Biome v2.1 中文网 - 粤ICP备13048890号