2022-02-07 call,apply,bind

三個(gè)函數(shù)都能改變this指向,且三者第一個(gè)參數(shù)都為指定的this對(duì)象。區(qū)別如下:
1、call 傳入?yún)?shù)列表,非數(shù)組; apply 參數(shù)格式為數(shù)組, bind參數(shù)列表。
2、call ,apply 為立即執(zhí)行函數(shù),bind 返回函數(shù)需要調(diào)用執(zhí)行。

call方法的實(shí)現(xiàn)

Function.prototype.myCall = function (context) {
      // 先判斷調(diào)用myCall是不是一個(gè)函數(shù)
      // 這里的this就是調(diào)用myCall的
      if (typeof this !== 'function') {
        throw new TypeError("Not a Function")
      }
      // 不傳參數(shù)默認(rèn)為window
      context = context || window
 
      // 保存this
      context.fn = this
 
      // 保存參數(shù)
      let args = Array.from(arguments).slice(1)   //Array.from 把偽數(shù)組對(duì)象轉(zhuǎn)為數(shù)組
 
      // 調(diào)用函數(shù)
      let result = context.fn(...args)
 
      delete context.fn
 
      return result
 
    }


apply方法的實(shí)現(xiàn)

Function.prototype.myApply = function (context) {
      // 判斷this是不是函數(shù)
      if (typeof this !== "function") {
        throw new TypeError("Not a Function")
      }
      let result
      // 默認(rèn)是window
      context = context || window
 
      // 保存this
      context.fn = this
      // 是否傳參
      if (arguments[1]) {
        result = context.fn(...arguments[1])
      } else {
        result = context.fn()
      }
      delete context.fn
      return result
    }

bind方法的實(shí)現(xiàn)


if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
 
    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP
                                 ? this
                                 : oThis || this,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };
 
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
 
    return fBound;
  };
}

注意:在非嚴(yán)格模式下,第一個(gè)參數(shù)沒傳默認(rèn)是window,在嚴(yán)格模式下是undefined,手寫沒考慮全面。

?著作權(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)容