JavaScript深入系列第十一篇,通過bind函數的模擬實現,帶大家真正了解bind的特性
bind一句話介紹 bind:
bind() 方法會創建一個新函數。當這個新函數被調用時,bind() 的第一個參數將作為它運行時的 this,之後的一序列參數將會在傳遞的實參前傳入作為它的參數。(來自於 MDN )
由此我們可以首先得出 bind 函數的兩個特點:
返回一個函數
可以傳入參數
返回函數的模擬實現從第一個特點開始,我們舉個例子:
var foo = {
value: 1
};
function bar() {
console.log(this.value);
}
var bindFoo = bar.bind(foo);
bindFoo();
關於指定 this 的指向,我們可以使用 call 或者 apply 實現,關於 call 和 apply 的模擬實現,可以查看《JavaScript深入之call和apply的模擬實現》。我們來寫第一版的代碼:
Function.prototype.bind2 = function (context) {
var self = this;
return function () {
return self.apply(context);
}
}
此外,之所以 return self.apply(context),是考慮到綁定函數可能是有返回值的,依然是這個例子:
var foo = {
value: 1
};
function bar() {
return this.value;
}
var bindFoo = bar.bind(foo);
console.log(bindFoo());
接下來看第二點,可以傳入參數。這個就有點讓人費解了,我在 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');
函數需要傳 name 和 age 兩個參數,竟然還可以在 bind 的時候,只傳一個 name,在執行返回的函數的時候,再傳另一個參數 age!
這可咋辦?不急,我們用 arguments 進行處理:
Function.prototype.bind2 = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var bindArgs = Array.prototype.slice.call(arguments);
return 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');
console.log(obj.habit);
console.log(obj.friend);
注意:儘管在全局和 foo 中都聲明了 value 值,最後依然返回了 undefind,說明綁定的 this 失效了,如果大家了解 new 的模擬實現,就會知道這個時候的 this 已經指向了 obj。
(哈哈,我這是為我的下一篇文章《JavaScript深入系列之new的模擬實現》打廣告)。
所以我們可以通過修改返回的函數的原型來實現,讓我們寫一下:
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);
return self.apply(this instanceof fBound ? this : context, args.concat(bindArgs));
}
fBound.prototype = this.prototype;
return fBound;
}
如果對原型鏈稍有困惑,可以查看《JavaScript深入之從原型到原型鏈》。
構造函數效果的優化實現但是在這個寫法中,我們直接將 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);
return self.apply(this instanceof fNOP ? 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,如果換成了 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 () {
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;
}