JavaScript深入系列第十一篇,通過bind函數(shù)的模擬實現(xiàn),帶大家真正了解bind的特性
bind
一句話介紹 bind:
bind() 方法會創(chuàng)建一個新函數(shù)。當這個新函數(shù)被調(diào)用時,bind() 的第一個參數(shù)將作為它運行時的 this,之后的一序列參數(shù)將會在傳遞的實參前傳入作為它的參數(shù)。(來自于 MDN )
由此我們可以首先得出 bind 函數(shù)的兩個特點:
- 返回一個函數(shù)
- 可以傳入?yún)?shù)
返回函數(shù)的模擬實現(xiàn)
從第一個特點開始,我們舉個例子:
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
// 返回了一個函數(shù)
var bindFoo = bar.bind(foo);
bindFoo(); // 1
關(guān)于指定 this 的指向,我們可以使用 call 或者 apply 實現(xiàn),關(guān)于 call 和 apply 的模擬實現(xiàn),可以查看《JavaScript深入之call和apply的模擬實現(xiàn)》。我們來寫第一版的代碼:
// 第一版
Function.prototype.bind2 = function (context) {
var self = this;
return function () {
return self.apply(context);
}
}
此外,之所以 return self.apply(context),是考慮到綁定函數(shù)可能是有返回值的,依然是這個例子:
var foo = {
value: 1
};
function bar() {
return this.value;
}
var bindFoo = bar.bind(foo);
console.log(bindFoo()); // 1
傳參的模擬實現(xiàn)
接下來看第二點,可以傳入?yún)?shù)。這個就有點讓人費解了,我在 bind 的時候,是否可以傳參呢?我在執(zhí)行 bind 返回的函數(shù)的時候,可不可以傳參呢?讓我們看個例子:
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
函數(shù)需要傳 name 和 age 兩個參數(shù),竟然還可以在 bind 的時候,只傳一個 name,在執(zhí)行返回的函數(shù)的時候,再傳另一個參數(shù) age!
這可咋辦?不急,我們用 arguments 進行處理:
// 第二版
Function.prototype.bind2 = function (context) {
var self = this;
// 獲取bind2函數(shù)從第二個參數(shù)到最后一個參數(shù)
var args = Array.prototype.slice.call(arguments, 1);
return function () {
// 這個時候的arguments是指bind返回的函數(shù)傳入的參數(shù)
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(context, args.concat(bindArgs));
}
}
構(gòu)造函數(shù)效果的模擬實現(xiàn)
完成了這兩點,最難的部分到啦!因為 bind 還有一個特點,就是
一個綁定函數(shù)也能使用new操作符創(chuàng)建對象:這種行為就像把原函數(shù)當成構(gòu)造器。提供的 this 值被忽略,同時調(diào)用時的參數(shù)被提供給模擬函數(shù)。
也就是說當 bind 返回的函數(shù)作為構(gòu)造函數(shù)的時候,bind 時指定的 this 值會失效,但傳入的參數(shù)依然生效。舉個例子:
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 的模擬實現(xiàn),就會知道這個時候的 this 已經(jīng)指向了 obj。
所以我們可以通過修改返回的函數(shù)的原型來實現(xiàn),讓我們寫一下:
// 第三版
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);
// 當作為構(gòu)造函數(shù)時,this 指向?qū)嵗?,此時結(jié)果為 true,將綁定函數(shù)的 this 指向該實例,可以讓實例獲得來自綁定函數(shù)的值
// 以上面的是 demo 為例,如果改成 `this instanceof fBound ? null : context`,實例只是一個空對象,將 null 改成 this ,實例會具有 habit 屬性
// 當作為普通函數(shù)時,this 指向 window,此時結(jié)果為 false,將綁定函數(shù)的 this 指向 context
return self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
}
// 修改返回函數(shù)的 prototype 為綁定函數(shù)的 prototype,實例就可以繼承綁定函數(shù)的原型中的值
fBound.prototype = this.prototype;
return fBound;
}
構(gòu)造函數(shù)效果的優(yōu)化實現(xiàn)
但是在這個寫法中,我們直接將 fBound.prototype = this.prototype,我們直接修改 fBound.prototype 的時候,也會直接修改綁定函數(shù)的 prototype。這個時候,我們可以通過一個空函數(shù)來進行中轉(zhuǎn):
// 第四版
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);
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
到此為止,大的問題都已經(jīng)解決,給自己一個贊!o( ̄▽ ̄)d
三個小問題
接下來處理些小問題:
1.apply 這段代碼跟 MDN 上的稍有不同
在 MDN 中文版講 bind 的模擬實現(xiàn)時,apply 這里的代碼是:
self.apply(this instanceof self ? this : context || this, args.concat(bindArgs))
多了一個關(guān)于 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!
所以這里不應(yīng)該進行 context 的判斷,大家查看 MDN 同樣內(nèi)容的英文版,就不存在這個判斷!
2.調(diào)用 bind 的不是函數(shù)咋辦?
不行,我們要報錯!
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 () {
var bindArgs = Array.prototype.slice.call(arguments);
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
作者:冴羽
github:https://github.com/mqyqingfeng/Blog
掘金主頁:https://juejin.im/user/58e4b9b261ff4b006b3227f4
segmentfault主頁:https://segmentfault.com/u/yayu/articles
Vicky丶Amor 經(jīng)授權(quán)轉(zhuǎn)載,版權(quán)歸原作者所有。
求關(guān)注,求點贊
