JavaScript:手動(dòng)實(shí)現(xiàn)call、apply、bind

  • call

1.把this增加到context this指向調(diào)用的方法
2.第0個(gè)傳入的是指向的對(duì)象,這里只需要調(diào)用方法傳入的形參
3.把截取的參數(shù)傳給執(zhí)行回調(diào)函數(shù)
4.刪除context上增加的fn方法

Function.prototype.myCall = function (context = window) {
  context.Fn = this 
  const args = [...arguments].splice(1) 
  const res = context.Fn(...args) 
  delete context.fn 
  return res
}
  • apply 跟call類似,前者傳多個(gè)參數(shù),后者傳入數(shù)組
Function.prototype.myApply = function (context = window) {
  context.Fn = this
  const args = [...arguments[1]] //傳入的數(shù)組拿出來(lái)
  const res = context.Fn(...args)
  delete context.fn
  return res
}
  • bind 返回一個(gè)函數(shù)

1.保存this指向的方法
2.把傳入的參數(shù)截取出來(lái)
3.返回一個(gè)函數(shù),在把call引入到里面,返回出來(lái)

Function.prototype.myBind = function (context = window) {
  const _this = this 
  const args = [...arguments].splice(1)
  return function (...args2) {
    //...[...args, ...args2] 可能存在多次調(diào)用,所以把兩者傳入的參數(shù)合二為一
    return _this.call(context, ...[...args, ...args2])
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容