手寫call、apply、bind函數(shù)

本文章用于個(gè)人筆記-內(nèi)容參考于掘金

  • 先看一下callapply、bind的應(yīng)用
function a(key,value){
  console.log(this.name)
  console.log(key)
  console.log(value)
}
var name = 'lv'
var obj = {
  name: 'yong'
}
a.call(obj,1,2)//'yong' 1 2
a.call(obj)//'yong' undefined undefined
a.apply(obj,[1,2])//'yong' 1 2
var b = a.bind(obj,1,2)
b()//'yong' 1 2
  • 手寫實(shí)現(xiàn)-call
Function.property.myCall = function(context){
  if(typeof this != 'function'){
    return throw new TypeError('Error')
  }
  context = context || window
  context.fn = this
  let args = context.slice(1)
  const result = context.fn(...arg)
  delete context.fn
  return result
}

-手寫實(shí)現(xiàn)-apply

Function.prototype.myApply = function(context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  context = context || window
  context.fn = this
  let result
  // 處理參數(shù)和 call 有區(qū)別
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }
  delete context.fn
  return result
}
  • 手寫實(shí)現(xiàn)-bind
Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  const _this = this
  const args = [...arguments].slice(1)
  // 返回一個(gè)函數(shù)
  return function F() {
    // 因?yàn)榉祷亓艘粋€(gè)函數(shù),我們可以 new F(),所以需要判斷
    if (this instanceof F) {
      return new _this(...args, ...arguments)
    }
    return _this.apply(context, args.concat(...arguments))
  }
}
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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