call apply bind

差異

bind 和 call 傳參方式一樣,但是bind返回的是一個函數(shù),綁定this,且可傳遞預(yù)置參數(shù)
call 和 apply 傳參方式不一樣,apply接收兩個參數(shù),第二個參數(shù)是一個參數(shù)數(shù)組
這三個都是用來重定義 this 這個對象的,下面的例子可以簡單看出幾個方法的不同

var student = {
  name: "高三學(xué)生",
  age:18,
  sayHi: function (province,city) {
    console.log("HI~我是" + this.name +",今年"+this.age+ ",來自" + province+city);
  },
};
var san = {
  name: "張三",
  age :20
};
student.sayHi.call(san,'湖南','長沙')
student.sayHi.apply(san,['湖南','長沙'])
student.sayHi.bind(san,'湖南','長沙')()
// 三個打印出來
// HI~我是張三,今年20,來自湖南長沙

實現(xiàn)這三個方法

Function.prototype.apply = function(context = window, args) {
  if (typeof this !== 'function') {
    throw new TypeError('Type Error');
  }
  const fn = Symbol('fn');
  context[fn] = this;

  const res = context[fn](...args);
  delete context[fn];
  return res;
}

Function.prototype.call = function(context = window, ...args) {
  if (typeof this !== 'function') {
    throw new TypeError('Type Error');
  }
  const fn = Symbol('fn');
  context[fn] = this;

  const res = context[fn](...args);
  delete context[fn];
  return res;
}

Function.prototype.bind = function(context, ...args) {
  if (typeof this !== 'function') {
    throw new Error("Type Error");
  }
  // 保存this的值
  var self = this;

  return function F() {
    // 考慮new的情況
    if(this instanceof F) {
      return new self(...args, ...arguments)
    }
    return self.apply(context, [...args, ...arguments])
  }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

  • 夜鶯2517閱讀 128,155評論 1 9
  • 版本:ios 1.2.1 亮點: 1.app角標可以實時更新天氣溫度或選擇空氣質(zhì)量,建議處女座就不要選了,不然老想...
    我就是沉沉閱讀 7,451評論 1 6
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,835評論 28 54
  • 兔子雖然是枚小碩 但學(xué)校的碩士四人寢不夠 就被分到了博士樓里 兩人一間 在學(xué)校的最西邊 靠山 兔子的室友身體不好 ...
    待業(yè)的兔子閱讀 2,767評論 2 9

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