跳到內容

unicorn/no-this-assignment 吹毛求疵

作用

禁止將 this 賦值給變數。

為什麼這是不好的?

this 賦值給變數是不必要的且令人困惑。

範例

此規則的不正確程式碼範例

javascript
const foo = this;
class Bar {
  method() {
    foo.baz();
  }
}

new Bar().method();

此規則的正確程式碼範例

javascript
class Bar {
  constructor(fooInstance) {
    this.fooInstance = fooInstance;
  }
  method() {
    this.fooInstance.baz();
  }
}

new Bar(this).method();

參考資料

以 MIT 授權發布。