MDN — this
(未完成)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
在 Javascript 中 this
與其他的語言會有點不太一樣,同時在 strict mode 和 non-strict mode 也有點不太一樣。
在大多數的情況下, this
的值取決於 function 是如何被呼叫的。除此之外 this
是不能被賦值,而且每次呼叫 function 時, this
也不見得會相同。
Global context
不論是不是在 strict mode ,在 global 的執行環境中(不在任何 function 內), this
是被指到 global object 。
Function context
在 function 中, this
的值取決於 function 如何被呼叫。
Simple call
底下的程式碼不是在 strict mode ,而且 this
也沒使用 call 來賦值,因此 this
會是 global object 。
但是,在 strict mode 中 this
的值會維持在進入執行環境時所設定的值,所以在這個例子中 this
在執行環境中並沒有定義,所以 this
就會是 undefined
。
在第二個範例中,
this
應該要是undefined
,因為f2
是直接被呼叫,也不是某個 object 的 method 或 property (例如:window.f2()
)
可以使用 call 或 apply 將 this
改成另一個:
使用 call 或 apply 呼叫 function 時,在 function 中 this
的值,會被綁定到一個特定的 object 來自 call 或 apply 。
注意:當使用 call 或 apply 時,如果傳入的值不是 object ,會企圖使用內部的 ToObject
轉成 object 。因此,如果傳入的原始值是 7
或是 'foo'
,將會使用相關的建構式轉成 object 。
像是 7
就會被轉成 new Number(7)
;而 'foo'
就會被轉成 new String('foo')
。
The bind
method
Arrow functions
arrow function 不會創建 this
,而是使用封閉環境中的 this
。
注意:在 arrow function 上使用 call 、 bind 或 apply 會被忽略