[JavaScript] 可以改變函數的動態 this — call()、apply()、bind()
這三個都是 JavaScript Function 的內建函式。
call()
The call()
method calls a function with a given this
value and arguments provided individually.
call() 方法會呼叫一個函式,搭配一個給定的 this
參數以及分別給定的參數。
語法:fun.call(thisArg[, arg1[, arg2[, ...]]])
thisArg
:給定的this
參數。arg1[, arg2[, ...]]
:分別給定的參數。
fun.call(thisArg, arg1, arg2)
也就是 this 為thisArg
的 fun(arg1, arg2)
。
apply()
The apply()
method calls a function with a given this
value, and arguments
provided as an array (or an array-like object).
apply() 方法會呼叫一個函式,搭配一個給定的 this
參數以及一組陣列形式的參數(或是一個 array-like object)。
語法:fun.apply(thisArg, [argsArray])
跟 call() 的不同是 apply() 只有兩個參數,把除了 this
的其他參數都整理在陣列。
fun.apply(thisArg, [argsArray])
等效 fun.call(thisArg, ...argsArray)
(ES6 以後的才可使用 “…”)。
例如 JavaScript 的變數 arguments,它會將傳進函式的變數整理成類陣列(Array-like
)物件,就可以這樣使用:
function func(argv0, argv1) { console.log(argv0, argv1);}
function apply_func() { return func.apply(this, arguments);}
// arguments = [1, 2]apply_func(1, 2); // 1 2
bind()
The bind()
method creates a new function that, when called, has its this
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
bind() 方法會建立一個新的函式,有他自己的 this
參數設置為給定的值,這個綁定的 this
無法再被修改。
當被呼叫時,搭配綁定的 this
與一個之前給定的順序的參數。
語法:fun.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg
綁定的this
參數。
除了 bind()
還有另外兩種方法可以固定住 this
:
- 利用 const context = this; 將
this
存在 context。 - 使用箭頭函式(arrow)。在 arrow 裡面的
this
永遠都是原先作用域的this
。