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