首先從以下幾點來考慮如何實現這幾個函數:
- 不傳入第一個參數,那麼上下文默認爲 window;
- 改變了 this 指向,讓新的對象可以執行該函數,並能接受參數。
那麼我們先來實現 call
Function.prototype.myCall = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
const args = [...arguments].slice(1)
const result = context.fn(...args)
delete context.fn
return result
}
分析:
- 首先 context 爲可選參數,如果不傳的話默認上下文爲 window;
- 接下來給 context 創建一個 fn 屬性,並將值設置爲需要調用的函數;
- 因爲 call 可以傳入多個參數作爲調用函數的參數,所以需要將參數剝離出來,然後調用函數並將對象上的函數刪除(因爲對象上本身是沒有這個函數的,只是在傳遞作用域調用時,做一個臨時屬性)。
以上就是實現 call 的思路,apply 的實現也類似,區別在於對參數的處理,所以就不一一分析思路了。
Function.prototype.myApply = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window
context.fn = this
let result
// 處理參數和 call 有區別
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn
return result
}
bind 的實現對比其他兩個函數略微地複雜了一點,因爲 bind 需要返回一個函數,需要判斷一些邊界問題,以下是 bind 的實現:
Function.prototype.myBind = function (context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
const _this = this
const args = [...arguments].slice(1)
// 返回一個函數
return function F() {
// 因爲返回了一個函數,我們可以 new F(),所以需要判斷
if (this instanceof F) {
return new _this(...args, ...arguments)
}
return _this.apply(context, args.concat(...arguments))
}
}
分析:
- 前幾步和之前的實現差不多,就不贅述了。
- bind 返回了一個函數,對於函數來說有兩種方式調用,一種是直接調用,一種是通過 new 的方式,我們先來說直接調用的方式;
- 對於直接調用來說,這裏選擇了 apply 的方式實現,但是對於參數需要注意以下情況:因爲 bind 可以實現類似這樣的代碼 f.bind(obj, 1)(2),所以我們需要將兩邊的參數拼接起來,於是就有了這樣的實現 args.concat(…arguments);
- 最後來說通過 new 的方式,對於 這種情況來說,不會被任何方式改變 this,所以對於這種情況我們需要忽略返回函數中的 this。