該來的還是得來。
簡述
呼叫 function 有三種方法:
- 用括號 
() - 用 
call - 用 
apply 
() 就是你常用的,所以不多做介紹,只會介紹 call 跟 apply 這兩個。
另外 bind 不是用來呼叫 function,是用來綁定 this 值的一種 method,並回傳一個新的 function。
跟 this 值有關的一些懶人包:
- 嚴格模式下,不是在物件裡的 
this值都是undefined - 非嚴格模式下,不是在物件裡的 
this值是 window / global(瀏覽器 / Node.js) - 非嚴格模式下,用 
callapplybind傳入的 primitive 都會被轉成 object - 如果傳 
nullundefined,非嚴格模式一律等於 window / global,嚴格等於nullundefined 
call 的用法
1  | function hello(a, b) { | 
第一個值是設定 this 值,待會再討論,第二個參數就是 function 中的參數了。
this 值要注意是不是「嚴格模式」:
- 在嚴格下,傳什麼就是什麼,傳 
null,undefined就會得到null,undefined - 在非嚴格下,傳進去 
nullundefined會得到global/window,而 primitive 都會變成 Object。 
1  | 'use strict'; | 
1  | function hello(a, b) { | 
apply 的用法
其實就跟 call 一模一樣,差別在於參數是用 Array 來傳入:
1  | function hello(a, b) { | 
一樣可以改 this 值,注意一下嚴格與非嚴格就好:
1  | 'use strict'; | 
1  | function hello(a, b) { | 
bind 的用法
前面有說過它是用來綁定 this 值的 method,因為是「綁定」,所以你就算之後再用 call 或 apply 也不會改變。
備註:用 bind 會回傳一個新的 function(綁定好 this 值再回傳)
1  | 'use strict' | 
1  | function hello() { | 
總之呢,你傳入的 this 值會根據嚴格或非嚴格模式定義,忘記的話就回去複習上面的例子。