導入
メソッドの中に出てくる this は、「その関数をどう呼んだか」で中身が決まります。定義した場所ではなく、呼び出し方が鍵です。ここを押さえると、よくある this のハマりどころを避けられます。
説明
オブジェクト.メソッド() の形で呼ぶと、this はそのオブジェクトを指します。
const user = {
name: "太郎",
greet() {
return `私は${this.name}`; // this = user
},
};
console.log(user.greet()); // 私は太郎
アロー関数は自分の this を持ちません。まわりのスコープの this をそのまま使います。この性質のおかげで、コールバックの中でも this がズレません。
const timer = {
seconds: 0,
tickAll() {
[1, 2, 3].forEach(() => {
this.seconds += 1; // アロー関数なので this は timer のまま
});
return this.seconds;
},
};
console.log(timer.tickAll()); // 3
もしここを普通の function () { ... } で書くと、その関数は自分の this を持ってしまい、this.seconds が timer を指さなくなります。**「コールバックはアロー関数で書く」**と覚えておくと安全です。
// アローなら親の this を引き継ぐので、下の書き方は正しく動く
const counter = {
n: 0,
addMany(list) {
list.forEach((v) => { this.n += v; });
return this.n;
},
};
console.log(counter.addMany([10, 20, 30])); // 60
やってみよう
user の name を書き換えて greet() の結果が変わることや、forEach の中を普通の関数にすると this がおかしくなることを試してみましょう。
演習
name に "ポチ" を持つオブジェクト dog を作り、this.name を使って ポチです と返すメソッド intro() を定義してください。intro() の結果を表示します。
ヒント1を見る
const dog = { name: "ポチ", intro() { return ${this.name}です; } }; console.log(dog.intro());