JavaScript深刻系列第十一篇,經過bind函數的模擬實現,帶你們真正瞭解bind的特性git
一句話介紹 bind:github
bind() 方法會建立一個新函數。當這個新函數被調用時,bind() 的第一個參數將做爲它運行時的 this,以後的一序列參數將會在傳遞的實參前傳入做爲它的參數。(來自於 MDN )markdown
由此咱們能夠首先得出 bind 函數的兩個特色:閉包
從第一個特色開始,咱們舉個例子:app
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 返回的函數的時候,可不能夠傳參呢?讓咱們看個例子:oop
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!post
這可咋辦?不急,咱們用 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 還有一個特色,就是this
一個綁定函數也能使用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。
(哈哈,我這是爲個人下一篇文章《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); // 看成爲構造函數時,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; }複製代碼
若是對原型鏈稍有困惑,能夠查看《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); 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; }複製代碼
《JavaScript深刻之call和apply的模擬實現》
JavaScript深刻系列目錄地址:github.com/mqyqingfeng…。
JavaScript深刻系列預計寫十五篇左右,旨在幫你們捋順JavaScript底層知識,重點講解如原型、做用域、執行上下文、變量對象、this、閉包、按值傳遞、call、apply、bind、new、繼承等難點概念。
若是有錯誤或者不嚴謹的地方,請務必給予指正,十分感謝。若是喜歡或者有所啓發,歡迎star,對做者也是一種鼓勵。