分析:bind函数目的是改变this指向,返回一个新的函数
假如我们有这么两个Object对象
const obj = {
name: 'obj'
}
const module = {
name: 'module',
getName: function (param, param2) {
console.log(param, param2)
return this.name
}
}
那么.bind绑定this输出来的结果是下面这样的:
const bound = module.getName.bind(obj, 'test')
console.log(bound(111)) //test 111 obj
那么很显然输出结果是这样的
那么接下来我们来自己写一个bind:
上代码
Function.prototype.mybind = function bind(thisArg) {
// 拿到传入的参数,把arguments变成一个真正的数组
// 可以通过Function.prototype验证arguments是否是真正的数组.arguments只是一个类数组,实际为object类型
//所以这里用借用数组的slice方法去获取他的参数,第一个是要绑定的this指向thisArg,所以要从第二个位置开始截取
const args = [].slice.call(arguments, 1);
// 记录它的调用者是谁
const self = this;
// 返回一个函数
return function () {
// 此函数的this指向thisArg,这里利用apply来扩展this指向
return self.apply(thisArg, args);
}
};
执行一下
const bound2 = module.getName.mybind(obj, 'test')
console.log(bound2(111)) //test undefined obj
发现绑定是没问题的,this.name输出的是obj ,但是呢后续传入的111没输出来且是undefined
那么我们再来修改一下:
Function.prototype.mybind = function bind(thisArg) {
// 拿到传入的参数,把arguments变成一个真正的数组
// 可以通过Function.prototype验证arguments是否是真正的数组.arguments只是一个类数组,实际为object类型
//所以这里用借用数组的slice方法去获取他的参数,第一个是要绑定的this指向thisArg,所以要从第二个位置开始截取
const args = [].slice.call(arguments, 1);
// 记录它的调用者是谁
const self = this;
// 返回一个函数
return function () {
//同样这里借用数组的concat和slice方法处理一下
const newargs = [].concat.call(args, [].slice.call(arguments, 0));
// 此函数的this指向thisArg,这里利用apply来扩展this指向
return self.apply(thisArg, newargs);
}
};