bind函数模拟实现
console.log(Function.prototype.bind) // function
console.log(Function.prototype.bind()) // function
console.log(Function.prototype.bind.name) // bind
console.log(Function.prototype.bind().name) // bound
以上可以看出bind是函数Function原型链上的属性,bind是一个函数,bind执行完之后返还得还是一个函数,改函数得名称为bound
bind函数使用动态的绑定this,相比很多写react的时候用过bind动态的绑定this,看下面的代码
var foo = {
name: 'wucr'
}
function getInfo(sex,age){
console.log(this.name,sex,age)
return false;
}
var bound = getInfo.bind(foo,'女');
var result = bound('12') // wucr 女 12
console.log(result) // false
根据以上运行得出结论
- bind函数里面的this指向它传递参数的第一个参数对象
- 在调用bind的时候参数也被接收了,也就是说bound函数里面的参数是别合并了
- bind后的返回值函数,执行后返回值是原函数(original)的返回值。
第一版bind实现
Function.prototype.bind1 = function(thisArg){
var args= [].slice.call(arguments,1) // 去除第一个参数的其他参数
var self = this;
console.log(this)
var bound = function(){
var boundArg = [].slice.call(arguments,0)
self.apply(thisArg,args.concat(boundArg))
}
return bound
}
以上就是初版bind的实现,但是有一个问题就是,bind返回的函数,有可能会被new 当作一个构造函来用,所以还是需要补充一下的方法
Function.prototype.bindFn = function(thisArg){
var args= [].slice.call(arguments,1) // 去除第一个参数的其他参数
var self = this;
var bound = function(){
var boundArg = [].slice.call(arguments,0)
var finalArg = args.concat(boundArg)
if(this instanceof bound ){
bound.prototype = Object.create(self.prototype);
var result = self.apply(this,finalArg )
if(typeof result === 'object' || typeof result === 'function'){
return result
}else{
return this;
}
}else{
return self.apply(thisArg,finalArg)
}
}
return bound
}