JavaScript深入之bind的模擬實現

JavaScript深入之bind的模擬實現

一句話介紹 bind:
bind() 方法會創建一個新函數。當這個新函數被調用時,bind() 的第一個參數將作爲它運行時的 this,之後的一序列參數將會在傳遞的實參前傳入作爲它的參數。(來自於 MDN )

由此我們可以首先得出 bind 函數的兩個特點:

  • 返回一個函數
  • 可以傳入參數

返回函數的模擬實現

從第一個特點開始,我們舉個例子:

var foo = {
    value: 1
};
function bar() {
    console.log(this.value);
}
// 返回了一個函數
var bindFoo = bar.bind(foo); 
bindFoo(); // 1

關於指定 this 的指向,我們可以使用 call 或者 apply 實現,關於 call 和 apply 的模擬實現,可以查看《JavaScript深入之call和apply的模擬實現》。我們來寫第一版的代碼:

// 第一版
Function.prototype.bind2 = function (context) {
    var self = this;
    return function () {
        self.apply(context);
    }
}

傳參的模擬實現

接下來看第二點,可以傳入參數。這個就有點讓人費解了,我在 bind 的時候,是否可以傳參呢?我在執行 bind 返回的函數的時候,可不可以傳參呢?讓我們看個例子:

var foo = {
    value: 1
};

function bar(name, age) {
    console.log(this.value);
    console.log(name);
    console.log(age);

}

var bindFoo = bar.bind(foo, 'daisy');
bindFoo('18');
// 1
// daisy
// 18

函數需要傳 name 和 age 兩個參數,竟然還可以在 bind 的時候,只傳一個 name,在執行返回的函數的時候,再傳另一個參數 age!
這可咋辦?不急,我們用 arguments 進行處理:

// 第二版
Function.prototype.bind2 = function (context) {

    var self = this;
    // 獲取bind2函數從第二個參數到最後一個參數
    var args = Array.prototype.slice.call(arguments, 1);

    return function () {
        // 這個時候的arguments是指bind返回的函數傳入的參數
        var bindArgs = Array.prototype.slice.call(arguments);
        self.apply(context, args.concat(bindArgs));
    }

}

構造函數效果的模擬實現

完成了這兩點,最難的部分到啦!因爲 bind 還有一個特點,就是

一個綁定函數也能使用new操作符創建對象:這種行爲就像把原函數當成構造器。提供的 this 值被忽略,同時調用時的參數被提供給模擬函數。

也就是說當 bind 返回的函數作爲構造函數的時候,bind 時指定的 this 值會失效,但傳入的參數依然生效。舉個例子:

var value = 2;

var foo = {
    value: 1
};

function bar(name, age) {
    this.habit = 'shopping';
    console.log(this.value);
    console.log(name);
    console.log(age);
}

bar.prototype.friend = 'kevin';

var bindFoo = bar.bind(foo, 'daisy');

var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin

注意:儘管在全局和 foo 中都聲明瞭 value 值,最後依然返回了 undefind,說明綁定的 this 失效了,如果大家瞭解 new 的模擬實現,就會知道這個時候的 this 已經指向了 obj。

所以我們可以通過修改返回的函數的原型來實現,讓我們寫一下:

// 第三版
Function.prototype.bind2 = function (context) {
    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fbound = function () {

        var bindArgs = Array.prototype.slice.call(arguments);
        // 當作爲構造函數時,this 指向實例,self 指向綁定函數,因爲下面一句 `fbound.prototype = this.prototype;`,已經修改了 fbound.prototype 爲 綁定函數的 prototype,此時結果爲 true,當結果爲 true 的時候,this 指向實例。
        // 當作爲普通函數時,this 指向 window,self 指向綁定函數,此時結果爲 false,當結果爲 false 的時候,this 指向綁定的 context。
        self.apply(this instanceof self ? this : context, args.concat(bindArgs));
    }
    // 修改返回函數的 prototype 爲綁定函數的 prototype,實例就可以繼承函數的原型中的值
    fbound.prototype = this.prototype;
    return fbound;
}

構造函數效果的優化實現

但是在這個寫法中,我們直接將 fbound.prototype = this.prototype,我們直接修改 fbound.prototype 的時候,也會直接修改函數的 prototype。這個時候,我們可以通過一個空函數來進行中轉:

// 第四版
Function.prototype.bind2 = function (context) {

    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fNOP = function () {};

    var fbound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        self.apply(this instanceof self ? this : context, args.concat(bindArgs));
    }
    fNOP.prototype = this.prototype;
    fbound.prototype = new fNOP();
    return fbound;

}

到此爲止,大的問題都已經解決,給自己一個贊!o( ̄▽ ̄)d

三個小問題

接下來處理些小問題:

1.apply 這段代碼跟 MDN 上的稍有不同

在 MDN 中文版講 bind 的模擬實現時,apply 這裏的代碼是:

self.apply(this instanceof self ? this : context || this, args.concat(bindArgs))

多了一個關於 context 是否存在的判斷,然而這個是錯誤的!
舉個例子:

var value = 2;
var foo = {
    value: 1,
    bar: bar.bind(null)
};
function bar() {
    console.log(this.value);
}
foo.bar() // 2

以上代碼正常情況下會打印 2,如果換成了 context || this,這段代碼就會打印 1!
所以這裏不應該進行 context 的判斷,大家查看 MDN 同樣內容的英文版,就不存在這個判斷!

2.調用 bind 的不是函數咋辦?

不行,我們要報錯!

if (typeof this !== "function") {
  throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}

3.我要在線上用

那別忘了做個兼容:

Function.prototype.bind = Function.prototype.bind || function () {
    ……
};

當然最好是用es5-shim啦。


最終代碼

所以最最後的代碼就是:

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 () {
        self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
    }

    fNOP.prototype = this.prototype;
    fbound.prototype = new fNOP();

    return fbound;

}

參考:https://blog.csdn.net/daimomo000/article/details/72897035
出處:未知

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