JavaScript | クラスのメソッドをイベントリスナーに登録するときの3つの方法を比較表

JavaScript JavaScript
スポンサーリンク

では「クラスのメソッドをイベントリスナーに登録するときの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 インスタンス
  }
}
JavaScript

2. アロー関数で呼び出す

class App {
  constructor(){
    this.button = document.getElementById("btn");
    this.button.addEventListener("click", (e) => this.handleClick(e));
  }
  handleClick(e){
    console.log("arrow:", this); // → App インスタンス
  }
}
JavaScript

3. クラスフィールドでアロー関数定義

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 をよく見かけます。

タイトルとURLをコピーしました