手寫實現apply,call,bind

手寫實現apply,call,bind

apply和call的區別就是傳的參數形式不一樣。call是一個一個的傳,apply可以將參數以數組的形式傳進去。而bind是傳入第二個和後面的參數,且綁定this,返回一個轉化後的函數。

考慮兩點

  • 第一個參數為undefined或null的時候,那麼會轉變為window
  • 改變了this執行,讓新的對象可以執行該函數。

call 實現

Function.prototype.myCall = function(context) {
// 判斷是否是undefined和null
if (typeof context === 'undefined' || context === null) {
context = window
}
context.fn = this
let args = [...arguments].slice(1)
let result = context.fn(...args)
delete context.fn
return result
}

apply的實現

Function.prototype.myApply = function(context) {
if (typeof context === 'undefined' || context === null) {
context = window
}
context.fn = this
let args = arguments[1]

let result
if (args) {
result = context.fn(...args)
} else {
result = context.fn()
}
delete context.fn
return result
}

bind實現

這裡需要注意下,因為bind轉換後的函數可以作為構造函數使用,此時this應該指向構造出的實例,而bind函數綁定的第一個參數。

Function.prototype.myBind = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
let _this = this
let args = [...arguments].slice(1)
return function F() {
// 判斷是否被當做構造函數使用
if (this instanceof F) {
return _this.apply(this, args.concat([...arguments]))
}
return _this.apply(context, args.concat([...arguments]))
}
}

參考鏈接:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

https://yuchengkai.cn/docs/zh/frontend/#call-apply-bind-區別

都看到這裡,轉發一下唄,關注並私信“前端資源”有小驚喜哦


分享到:


相關文章: