bind - 2020-11-03

https://zhuanlan.zhihu.com/p/85438296

Function.prototype.bind2 = function(context) {

  if (typeof this !== "function") {
    throw new Error(
      "Function.prototype.bind - what is trying to be bound is not callable"
    );
  }
  
  var self = this;
  var args = Array.prototype.slice.call(arguments, 1)

  var fNOP = function () {};

  var fBound = function () {
    var bindArgs = Array.prototype.slice.call(arguments);
    // 當(dāng)作為構(gòu)造函數(shù)時(shí),this 指向?qū)嵗藭r(shí)結(jié)果為 true,將綁定函數(shù)的 this 指向該實(shí)例,可以讓實(shí)例獲得來自綁定函數(shù)的值
    // 以上面的是 demo 為例,如果改成 `this instanceof fBound ? null : context`,實(shí)例只是一個(gè)空對象,將 null 改成 this ,實(shí)例會(huì)具有 habit 屬性
    // 當(dāng)作為普通函數(shù)時(shí),this 指向 window,此時(shí)結(jié)果為 false,將綁定函數(shù)的 this 指向 context
    return self.apply(
      this instanceof fBound ? this : context,
      args.concat(bindArgs)
    );
  };
  // 修改返回函數(shù)的 prototype 為綁定函數(shù)的 prototype,實(shí)例就可以繼承綁定函數(shù)的原型中的值
  fNOP.prototype = this.prototype;
  fBound.prototype = new fNOP();
  return fBound;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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