箭頭函式的this
箭頭函式的this
在 JavaScript 中遇到 this ,有 2 件事情要注意:
- this 代表的是 function 執行時所屬的物件,而不是 function 本身。
- 沒有特別指定 this 的情況下,this 預設綁定( Default Binding )「全域物件」,也就是 window。
物件調用與 Simple Call
先來看看 simple call 跟物件調用的狀況:
var universe = '漫威宇宙';
// 用 var 才會是全域變數
function callHero() {
console.log(this.universe);
}
const ironMan = {
universe : '鋼鐵人宇宙',
callHero
}
ironMan.callHero();
// this 指向調用 callHero() 的 ironMan
var spiderMan = {
universe : '蜘蛛人宇宙',
callHero,
stranger(){
callHero(); // simple call
}
}
spiderMan.callHero();
// 蜘蛛人宇宙,調用 callHero() 的是 spiderMan 這個物件
// 所以 this 指向 spiderMan
spiderMan.stranger();
// 漫威宇宙,因為調用 callHero() 的是 stranger()這個函式
// 所以 this 指向全域,也就是 window
箭頭函式的 this
當 this 出現在箭頭函式中,因為箭頭函式沒有自己的 this ,所以會指向外層。
一樣設一個全域變數與一個 callHero()函式。
var universe = '漫威宇宙';
// 用 var 才會指向全域
function callHero() {
console.log(this.universe);
}
var spiderMan = {
universe : '蜘蛛人宇宙',
callHero,
stranger:() => {
console.log(this.universe)
}
// 箭頭函式沒有自己的 this ,所以指向外層,也就是全域
}
spiderMan.callHero();
//蜘蛛人宇宙
spiderMan.stranger();
//漫威宇宙
callBack function 中的 this
var universe = '漫威宇宙';
// 用 var 才會指向全域
function callHero() {
console.log(this.universe);
}
const spiderMan = {
universe : '蛛蛛人宇宙',
callHero: function(){
console.log('1',this.universe);
// 1 蜘蛛人宇宙
setTimeout(function (){
console.log('2',this.universe);
// 2 漫威宇宙
console.log('3',this);
// 3 window
})
}
}
spiderMan.callHero();
但是 callBack function 被包在一個物件屬性的函式 callHero 中,當 spiderMan.callHero()
,也就是spiderMan 調用 callHero()的時候,setTimeout 是被 callHero 這個函式所調用,這時 this 指向全域的 window。
同樣的例子,在 setTimeout() 中改用箭頭函式,則 this 會指向外層,也就是調用他的物件– spiderMan 這個物件。
var universe = '漫威宇宙';
// 用 var 才會指向全域
function callHero() {
console.log(this.universe);
}
const spiderMan = {
universe : '蛛蛛人宇宙',
callHero: function(){
console.log('1',this.universe);
// 1 蜘蛛人宇宙
setTimeout(() => {
console.log('2',this.universe);
// 2 蛛蛛人宇宙
console.log('3',this);
// 3 {universe: '蛛蛛人宇宙', callHero: ƒ}
})
}
}
spiderMan.callHero();
箭頭函式的this
https://popeye-ux.github.io/2022/10/19/thisInArrowFunction/