用法
我们先来看个小例子
var age= 1;
var obj = {
age: 2,
say: functino () {
console.log(this.age)
}
}
obj.say(); // 1
obj.bind(window);
obj.say(); // 2
从上面的例子我们可以看出,bind 的作用就是为了修改函数内部 this 的指向。如上面的例子中,经过 obj.bind(window) 之后,obj.say 函数中的 this 指向了 window
实现
我们来看一下自己怎么实现这个bind函数
Function.prototype.bind = function (context) {
var self = this;
return function () {
self.apply(context, arguments)
}
}
利用 apply 函数,改变函数内部 this 指向。但是这个时候 bind 函数是没法传递其他参数的,如果要传递其他函数,我们需要做一点改造
Function.prototype.bind = function () {
var self = this;
var context = Array.prototype.shift.call(arguments); // 拿到上下文对象
var args = Array.prototype.slice(arguments); // 拿到其他参数
return function () {
self.apply(context, Array.prototype.concat.call(args, Array.prototype.slice(arguments)))
}
}