如何使用50行javaScript代碼實現簡單版的call,apply,bind

這篇文章主要介紹了50行javaScript代碼實現簡單版的call,apply,bind過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

在實現自己的call,apply,bind前,需要複習一下this.

所謂的this其實可以理解成一根指針:

其實 this 的指向,始終堅持一個原理:this 永遠指向最後調用它的那個對象,這就是精髓。最關鍵所在

this的四種指向:

當this所在的函數被普通調用時,指向window,如果當前是嚴格模式,則指向undefined

function test() {
 console.log(this);
};

test();
指向window 輸出下面的代碼:
// Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
嚴格模式
'use strict';
function test() {
 console.log(this);
};
test();
// undefined

當this所在當函數被以obj.fn()形式調用時,指向obj

var obj = {
 name: 'segmentFault',
 foo: function() {
  console.log(this.name);
 }
}
obj.foo();
// 'segmentFault'

還可以這麼做

function test() {
 console.log(this.name);
}
var obj = {
 name: 'qiutc',
 foo: test
}
obj.foo();
// 'qiutc'

當call,apply加入後,this的指向被改變了

 function a(a,b,c) {
    console.log(this.name);
    console.log(a,b,c)
  }
  const b = {
    name: "segmentFault"
  }
  a.call(b,1,2,3)    
  //輸出 segmentFault和 1,2,3
  function a(a,b,c) {
    console.log(this.name);
    console.log(a,b,c)
  }
  a.apply(b,[1,2,3])
  //輸出segmentFault和1,2,3

遇到bind後 :

  function a() {
    console.log(this.name);
  }
  const b = {
    name: "segmentFault"
  }
  a.bind(b, 1, 2, 3)

此時控制檯並沒有代碼輸出,因爲bind會重新生成並且返回一個函數,這個函數的this指向第一個參數

  function a() {
    console.log(this.name);
  }
  const b = {
    name: "segmentFault"
  }
  const c = a.bind(b, 1, 2, 3)
  c()
  //此時輸出segmentFault

正式開始自己實現call :

在函數原型上定義自己的myCall方法:

 Function.prototype.myCall = function (context, ...arg) {
    const fn = Symbol('臨時屬性')
    context[fn] = this
    context[fn](...arg)
    delete context[fn]
  }

四行代碼實現了簡單的call,思路如下:

  • 通過對象屬性的方式調用函數,這個函數裏面的this指向這個對象
  • 每次調用新增一個symbol屬性,調用完畢刪除
  • 這個symbol屬性就是調用mycall方法的函數
  • 函數形參中使用...arg是將多個形參都塞到一個數組裏,在函數內部使用arg這個變量時,就是包含所有形參的數組
  • 在調用 context[fn](...arg)時候,...arg是爲了展開數組,依次傳入參數調用函數

爲了簡化,今天都不做類型判斷和錯誤邊際處理,只把原理講清楚。

自己實現apply

在函數原型上定義自己的myApply方法:

//實現自己的myApply
  Function.prototype.myApply = function (context, arg) {
    const fn = Symbol('臨時屬性')
    context[fn] = this
    context[fn](...arg)
    delete context[fn]
  }
  const obj2 = {
    a: 1
  }
  test.myApply(obj2, [2, 3, 4])

同理,只是apply傳遞的第二個參數是數組,這裏我們只需要在調用時,將參數用...把數組展開即可

自己實現bind:

bind跟apply,call的本質區別,bind不會改變原函數的this指向,只會返回一個新的函數(我們想要的那個this指向),並且不會調用。但是apply和bind會改變原函數的this指向並且直接調用

bind在編寫框架源碼,例如koa等中用得特別多:

 //實現自己的myBind
  Function.prototype.myBind = function (context, ...firstarg) {
    const that = this
    const bindFn = function (...secoundarg) {
      return that.myCall(context, ...firstarg, ...secoundarg)
    }
    bindFn.prototype = Object.create(that.prototype)
    return bindFn
  }

  var fnbind = test.myBind(obj, 2)
  fnbind(3)

同理 自己定義好原型上的myBind方法

this劫持 保留最初的調用mybind方法的那個對象

返回一個新的函數 這個新的函數內部this指向已經確定,使用的是我們的mycall方法

學習需要循序漸進,建議根據本文順序去封裝一遍,是比較輕鬆的,當然bind還需要判斷是否是new調用.

完整版本bind

Function.prototype.myBind = function (objThis, ...params) {
  const thisFn = this; // 存儲源函數以及上方的params(函數參數)
  // 對返回的函數 secondParams 二次傳參
  let fToBind = function (...secondParams) {
    console.log('secondParams',secondParams,...secondParams)
    const isNew = this instanceof fToBind // this是否是fToBind的實例 也就是返回的fToBind是否通過new調用
    const context = isNew ? this : Object(objThis) // new調用就綁定到this上,否則就綁定到傳入的objThis上
    return thisFn.call(context, ...params, ...secondParams); // 用call調用源函數綁定this的指向並傳遞參數,返回執行結果
  };
  fToBind.prototype = Object.create(thisFn.prototype); // 複製源函數的prototype給fToBind
  return fToBind; // 返回拷貝的函數
};

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章