💬
JavaScript「this」とbind(this)
毎回わからなくなるthisとbindについてのメモ書き
thisの基本
JavaScriptでの「this」は関数の呼び出し方によって参照先が変わる:
- イベントリスナー:イベントが発生した要素を参照
bind(this)の役割
bind(this)
は関数内のthis
の参照先を固定する。
// 例:クラス内でのbind(this)
class Counter {
count = 0;
constructor() {
const button = document.querySelector('button');
// thisを固定する場合
button.addEventListener('click', this.increment.bind(this));
// thisを固定しない場合(問題あり)
// button.addEventListener('click', this.increment);
}
increment() {
this.count += 1;
console.log(this.count);
}
}
問題と解決策
問題
button.addEventListener('click', this.increment)
とすると、increment
メソッド内のthis
はボタン要素を参照する。ボタンにはcount
プロパティがないのでエラーになる。
解決策1: bind(this)
button.addEventListener('click', this.increment.bind(this))
とすると、increment
メソッド内のthis
はクラスのインスタンスを参照する。
解決策2: アロー関数
class Counter {
count = 0;
constructor() {
const button = document.querySelector('button');
button.addEventListener('click', this.increment);
}
// アロー関数を使うと自動的にthisが固定される
increment = () => {
this.count += 1;
console.log(this.count);
}
}
まとめ
-
bind(this)
:関数内のthis
を呼び出し元のコンテキスト(多くの場合はクラスのインスタンス)に固定する - 用途:イベントリスナーやコールバック関数でクラスのメソッドを使うとき
- 代替手段:アロー関数を使うと、
bind(this)
を使わなくても同様の効果が得られる
Discussion