アロー関数式のthis参照
var value = 100; // ①
const obj = {
value: 1000, // ②
delay() {
_this = this;
// 既存の関数の定義の場合、setTimeoutのfunctionではグローバル変数の①をthisで参照する
setTimeout(function() {
console.log(this.value, _this.value);
}, this.value); // 100 1000
// アロー関数式の場合、関数の定義されたオブジェクトがthisになる。
setTimeout(() => console.log(this.value, _this.value), this.value); // 1000 1000
}
}
obj.delay();アロー関数式のメリット
・関数を簡略して書ける
・thisを束縛できる