1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【typescript】thisはstatic メソッド内だとクラスを指す

Posted at

勘違いしてたこと

class Me {
  static firstName = "Atsushi";

  static work() {
    return `Hey! I'm ${this.firstName}`;
  }
}

「参照先がstaticなのに this を使ってるの、おかしくない?」
「thisってインスタンスじゃないの?」

と思うかもしれません。でもこれは正しい書き方です。


結論:staticメソッド内のthisはクラス自身

公式な動作として、static メソッド内での thisインスタンスではなくクラス自身を指します

つまり、次の2つはまったく同じ意味です。

return this.firstName;
return Me.firstName;

staticメソッドはインスタンスではなく自身のクラスに紐づくというわけです。

基本的にはthis使う

  • クラス名を直書き(例:Me.firstName)すると、将来的にクラス名を変更したとき修正が面倒。
  • this.firstName にしておけば、クラス名を変更しても内部で自動的に反映される。

📚 引用元

サバイバルTypeScript

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?