bind {
解決問題:callback() { this ? //誰在用 }
}app
function callback() { console.log(this); } function foo(cb) { cb(); } foo(callback); // 輸出的this是誰的呢? => 全局window的 foo(callback.bind(callback)); // 輸出的this是誰的呢? => callback的 foo(callback.bind(foo)); // 輸出的this是誰的呢? => foo的
來看個具體的問題(後面就舉了個例子,沒興趣的能夠到此爲止了。篇幅比較短,見諒) =>函數
// 把['x','y',1,2]拷貝到lost.arr中 var lost = { arr : [], pushArray: function(s) { this.arr.push(s); } }; // error 不認識arr // 由於做用域問題。如今調用pushArray的對象是window,而window是沒有arr的 ['x','y',1,2].forEach(lost.pushArray);
那麼怎麼就能證實是window對象調用了lost.pushArray呢。this
window.arr = []; ['x','y',1,2].forEach(lost.pushArray); console.log(window.arr);
其實看看上面的丟失緣由以後,就知道了其實pushArray的使用權被window對象奪去了,而咱們須要讓lost奪回pushArray的使用權。spa
// 在覈心代碼前,加一層殼(匿名函數),讓window使用這個匿名函數,就解決了 ['x','y',1,2].forEach(function(s) { // 匿名函數 // 核心代碼 lost.pushArray(s); });
使用bind就比較優雅了。code
['x','y',1,2].forEach(lost.pushArray.bind(lost));
結合第一種解決方法,大膽的猜想,bind的僞實現能夠是,至關於返回一個匿名函數。對象
function bind(me) { var fn = this; return function() { fn.apply(me, arguments); } }
驗證一下,哈哈,結果和bind同樣喲。ip