this: コンテキストの理解

this は呼び出し方で変わる。bind/アロー関数で制御。

this
現在のオブジェクトへの参照。
bind
this を固定した新しい関数を作成。
アロー関数
this を継承(定義時のコンテキスト)。

this とは?

役者の台本 (Actor's Script)

`this` は台本にある「私(I)」という言葉のようなものです。誰が(どのオブジェクトが)その台本を読むかによって、「私」が指す人物が変わります。メソッドをそのまま呼び出せばそのオブジェクトが「私」ですが、関数だけを取り出して別の場所で読むと、「私」が誰かわからなくなったり、別人(Global/Window)になったりします。

JavaScript で最も混乱しやすい概念の一つです。`function` キーワードで定義された関数では、`this` は「呼び出された時の文脈(実行コンテキスト)」で決まります。一方、アロー関数(`=>`)は「定義された場所の文脈」をそのまま固定して記憶する(レキシカルスコープ)ため、直感的で安全です。

this Basics
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, bind, arrow
// call / apply / bind
function 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 を固定してください。