では「クラスのメソッドをイベントリスナーに登録するときの3つの方法」を比較表で整理してみましょう。これで状況に応じてどの書き方を選べばよいか一目で分かります。
クラスのメソッドと this の扱い比較
| 方法 | 書き方 | this の指すもの | メリット | デメリット |
|---|---|---|---|---|
| bind を使う | this.handleClick.bind(this) | クラスのインスタンス | 明示的で分かりやすい | 毎回 bind が必要、コードが少し冗長 |
| アロー関数で呼び出す | (e) => this.handleClick(e) | 外側の this(インスタンス) | 簡単に書ける、柔軟 | 無名関数なので removeEventListener で外せない |
| クラスフィールドでアロー関数定義 | handleClick = (e) => { ... } | 常にインスタンス | モダンでシンプル、removeEventListener も可能 | 古い環境では使えない場合あり(Babel等必要) |
コード例
1. bind を使う
class App {
constructor(){
this.button = document.getElementById("btn");
this.button.addEventListener("click", this.handleClick.bind(this));
}
handleClick(e){
console.log("bind:", this); // → App インスタンス
}
}
JavaScript2. アロー関数で呼び出す
class App {
constructor(){
this.button = document.getElementById("btn");
this.button.addEventListener("click", (e) => this.handleClick(e));
}
handleClick(e){
console.log("arrow:", this); // → App インスタンス
}
}
JavaScript3. クラスフィールドでアロー関数定義
class App {
constructor(){
this.button = document.getElementById("btn");
this.button.addEventListener("click", this.handleClick);
}
handleClick = (e) => {
console.log("class field:", this); // → App インスタンス
}
}
JavaScript✅ まとめ
- bind:古典的で確実。
- アロー関数で呼び出す:簡単だが removeEventListener で外せない点に注意。
- クラスフィールドでアロー関数:モダンで一番シンプル。React などでもよく使われる。
💡 実務では「クラスフィールド+アロー関数」が主流ですが、古いコードやライブラリでは bind をよく見かけます。


