天天看點

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; // 傳回拷貝的函數
};           

複制

覺得寫得不錯可以給個

star

,歡迎加入我們的前端交流群~: