回到文章列表

簡單整理如何判斷 this 的值

TWGD / 2019-01-08

記住一個大原則

this 的值只與『呼叫的方法』有關係。 this 的值只與『呼叫的方法』有關係。 this 的值只與『呼叫的方法』有關係。

記住如何轉換成 call ( 或 apply) 形式

轉換:

func(a, b) --> func.call( undefined, a, b)
//  嚴格模式下:undefined;非嚴格模式:依環境預設值定義。

obj.method(a, b) --> obj.method.call( obj, a, b)

this 就是 call() 或 apply() 傳入的第一個參數

this 就是 call function 傳入的第一的參數 this 就是 call function 傳入的第一的參數 this 就是 call function 傳入的第一的參數

其他:

DOM 操作

簡單來說,this 是被綁定的 target。

強制綁定

thisbind() 裡面傳入的值。

arrow function

特例:this 的值與『如何定義』有關係。是 function 被定義的地方的 this 值。


參考資料:

  • https://zhuanlan.zhihu.com/p/23804247
  • https://zhuanlan.zhihu.com/p/25991271