Arrow Function - This

觀念

  • arrow function 的 this 是依據環境的父層區域來綁定。意思為arrow function 定義位置的上一層 this 代表誰,arrow function 內的 this 就代表誰

var a = 1;
function funcA(){
	console.log(this.a)
    let arrA = ()=> console.log(this.a)
    arrA()
}
let objA = {
    a:2,
	funcA: funcA
}
//直接呼叫的狀況,this 是 window,裡面的 arrow function 也抓到 window
funcA()
// 1
// 1

// 改為透過 objA 去呼叫,this 變成 objA,arrow function 也抓到 objA
objA.funcA()
// 分析過程
// 1. 物件內將 funcA 分配為 funA()
// 2. 為非自己宣告,故可以指向objA
// 2
// 2

from 卡斯伯的教學

不是建立在物件內的函式,不會影響箭頭函式的 this

不可使用

於 call()、apply()、bind()

from 箭頭函數 Arrow Function

於 new 建構函數

於 prototype 方法

Last updated

Was this helpful?