call, apply, bind

call, apply, bind 區別

首先說下前二者的區別。
call 和 apply 都是爲了解決改變 this 的指向。做用都是相同的,只是傳參的方式不一樣。
除了第一個參數外,call 能夠接收一個參數列表,apply 只接受一個參數數組。數組

模擬實現 call 和 apply

能夠從如下幾點來考慮如何實現
不傳入第一個參數,那麼默認爲 window
改變了 this 指向,讓新的對象能夠執行該函數。那麼思路是否能夠變成給新的對象添加一個函數,而後在執行完之後刪除app

Function.prototype.myCall = function (context) {
  var context = context || window
  // 給 context 添加一個屬性
  // getValue.call(a, 'yck', '24') => a.fn = getValue
  context.fn = this
  // 將 context 後面的參數取出來
  var args = [...arguments].slice(1)
  // getValue.call(a, 'yck', '24') => a.fn('yck', '24')
  var result = context.fn(...args)
  // 刪除 fn
  delete context.fn
  return result
}

以上就是 call 的思路,apply 的實現也相似函數

Function.prototype.myApply = function (context) {
  var context = context || window
  context.fn = this

  var result
  // 須要判斷是否存儲第二個參數
  // 若是存在,就將第二個參數展開
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }

  delete context.fn
  return result
}

bind 和其餘兩個方法做用也是一致的,只是該方法會返回一個函數。而且咱們能夠經過 bind 實現柯里化。
一樣的,也來模擬實現下 bindthis

Function.prototype.myBind = function (context) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  var _this = this
  var 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))
  }
}
相關文章
相關標籤/搜索