this: コンテキストの理解
this は呼び出し方で変わる。bind/アロー関数で制御。
this
現在のオブジェクトへの参照。
bind
this を固定した新しい関数を作成。
アロー関数
this を継承(定義時のコンテキスト)。
this とは?
JavaScript で最も混乱しやすい概念の一つです。`function` キーワードで定義された関数では、`this` は「呼び出された時の文脈(実行コンテキスト)」で決まります。一方、アロー関数(`=>`)は「定義された場所の文脈」をそのまま固定して記憶する(レキシカルスコープ)ため、直感的で安全です。
const user = { name: 'Alice', greet() { console.log(`Hi, I'm ${this.name}`); }};
user.greet(); // "Hi, I'm Alice"
// メソッドを変数に代入すると this が失われるconst greet = user.greet;greet(); // "Hi, I'm undefined" — this が window になるBad
// ❌ Bad: this が失われるbutton.addEventListener('click', user.greet);// this は button になるGood
// ✅ Good: bind で this を固定button.addEventListener('click', user.greet.bind(user));
// または アロー関数button.addEventListener('click', () => user.greet());this の束縛
// call / apply / bindfunction greet(greeting) { console.log(`${greeting}, ${this.name}`);}
greet.call({ name: 'Bob' }, 'Hello'); // "Hello, Bob"greet.apply({ name: 'Carol' }, ['Hi']); // "Hi, Carol"const boundGreet = greet.bind({ name: 'Dave' });boundGreet('Hey'); // "Hey, Dave"
// アロー関数: this を継承(束縛しない)const obj = { name: 'Eve', delayed() { setTimeout(() => { console.log(this.name); // "Eve" — 外側の this }, 100); }}; Tip: クラスのメソッドはアロー関数で定義すると this が安定。
合格ライン
this が失われるケースを説明できる
bind とアロー関数を使い分けられる
演習課題
課題1: this の確認
this が失われるケースを再現してください。
課題2: bind と arrow
bind とアロー関数で this を固定してください。