當在function內使用this,而這個function 定義位置在method內,例如:
1 2 3 4 5 6 7 8 9 10 11
| const obj = { func1() { console.log('func1 this', this); (function func2() { console.log('func2 this', this); })(); } };
obj.func1();
|
這個functoin內的this指向的會是全域物件window,而不是預期指向obj,這是JS本身就存在的BUG,
但在ES6箭頭函式的出現,有解決掉這個BUG,原因是箭頭函式定義位置的上一層regular function & method的 this
代表誰,箭頭函式內的 this
就代表誰。
1 2 3 4 5 6 7 8 9 10 11
| const obj = { func1() { console.log('func1 this', this); (() => { console.log('func2 this', this); })(); } };
obj.func1();
|
再看一個範例:
在一般函式下
1 2 3 4 5 6 7 8
| const person = { firstName: 'Bob', getName() { console.log(this.firstName); } };
person.getName();
|
使用箭頭函式
1 2 3 4 5 6 7 8
| const person = { firstName: 'Bob', getName: () => { console.log(this.firstName); } };
person.getName();
|