this
物件。this
的例子,可以發現和傳統函數的 this
運作原則大不相同。this
判斷原則MDN & W3Schools:
In arrow functions, this retains the value of the enclosing lexical context's this. Arrow functions do not have their own this. In global code, it will be set to the global object.
this
和傳統函數的一個重大差異就是看的是語彙位置。this
引用物件,指向當下的呼叫者。this
引用物件,呼叫 this
時,會沿用語彙環境外圍的 this
。this
的情境範例,換成 Arrow Functions 的狀況,並和傳統函數做比對。player.whatsThis()
的呼叫者就是 player
:whatsThis()
使用 Arrow Functions 定義,因此 whatsThis()
本身不會有自己的 this
,而是沿用外圍環境的 this
。whatsThis()
再往外一層不在任何 Function Context 內,換言之就是 Global Context。在全域環境裡的 this
就是 Global 物件,在 HTML 裡就是 window
:player.f()
的呼叫者就是 player
:player.f()
呼叫,但這邊看的是語彙位置,whatsThis()
再往外一層的 this
是 Global 物件:obj.method()
的公式,呼叫者同樣很好辨認:player.f()
和 player.pet.f()
語彙位置再往外一層其實都是 Global Context,所以兩個函數回傳的 this
都是 Global 物件:undefined
:this
都是 Global 物件:obj.f()
,因此 this
是呼叫者 obj
物件,this.x
是 20。foo()
,視同簡單呼叫,一般模式下 this
是 Global 物件,因此 this.x
是 10。this.x
不變仍是 20。this
,其外層就是 obj.f()
,因此 this.x
也是 20。foo()
,視同簡單呼叫,一般模式下 this
是 Global 物件,因此 this.x
是 10。this
,往外找一層是 Global Context,所以 this
也是 Global 物件。this
,往外找一層是 Global Context,所以 this
也是 Global 物件。this
,其外層是 obj.f()
;而 obj.f()
的 this
如上面所說,經過沿用後是 Global 物件。可以發現上面第 2 和 第 3 個情境的結果都是 Output#1 和 Output#2 等於 10。雖然他們最後呈現的結果碰巧一樣,但要注意背後的運作原理其實有所差別。