bind()
最简单的用法是创建一个函数,使这个函数不论怎么调用都有同样的
this
值。
常见错误
常见的错误就是将方法从对象中拿出来,然后调用,并且希望this
指向原来的对象。错误示范如下:
var altwrite = document.write;
altwrite("hello");//报错
因为altwrite
方法是在window
上进行调用的,函数内部的this
指向的是window
而不再是document
,自然就报错啦,正确的写法应该是:
altwrite.bind(document)("hello")
常见使用
bind()
使用方法如下:
this.num = 9;
var mymodule = {
num: 81,
getNum: function() { return this.num; }
};
var getNum = mymodule.getNum;
getNum(); // 9, 因为在这个例子中,"this"指向全局对象
// 创建一个'this'绑定到module的函数
var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81
注意:一般情况下setTimeout()
的this
指向window
对象。当使用类的方法时需要this
指向类实例,就可以使用bind()
将this
绑定到回调函数来管理实例。
实现
Function.prototype.bind = function (context) {
var self = this;
return function () {
self.apply(context);
}
}
如果bind()
函数还要传参呢?
Function.prototype.bind = 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));
}
}
function a(m, n, o) {
console.log(this.name + ' ' + m + ' ' + n + ' ' + o);
}
var b = {
name: 'kong'
};
a.bind(b, 7, 8)(9) // kong 7 8 9
核心就是使用apply()
方法