no-this-before-super
不允許在建構函式中呼叫 super()
之前使用 this
/super
✅ 建議使用
在設定檔中使用來自 @eslint/js
的 recommended
設定會啟用此規則
在衍生類別的建構函式中,如果在呼叫 super()
之前使用 this
/super
,則會引發參考錯誤。
此規則會檢查建構函式中的 this
/super
關鍵字,然後回報那些在 super()
之前的關鍵字。
規則細節
此規則旨在標記在呼叫 super()
之前的 this
/super
關鍵字。
範例
此規則的不正確程式碼範例
在遊樂場中開啟
/*eslint no-this-before-super: "error"*/
class A1 extends B {
constructor() {
.a = 0;
super();
}
}
class A2 extends B {
constructor() {
.foo();
super();
}
}
class A3 extends B {
constructor() {
.foo();
super();
}
}
class A4 extends B {
constructor() {
super(.foo());
}
}
此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-this-before-super: "error"*/
class A1 {
constructor() {
this.a = 0; // OK, this class doesn't have an `extends` clause.
}
}
class A2 extends B {
constructor() {
super();
this.a = 0; // OK, this is after `super()`.
}
}
class A3 extends B {
foo() {
this.a = 0; // OK. this is not in a constructor.
}
}
何時不使用
如果您不想收到關於在建構函式中使用 this
/super
在 super()
之前的通知,您可以安全地停用此規則。
由 TypeScript 處理
當使用 TypeScript 時,停用此規則是安全的,因為 TypeScript 的編譯器會強制執行此檢查。
版本
此規則是在 ESLint v0.24.0 中引入的。