首先我们要明白bind,apply和call的区别
var obj = {
name:'tom',
say:function(a,b){
console.log(this.age,a,b)
}
}
var obj2 = {
age:20
}
obj.say.call(obj2,'call',1) //20 ‘call' 1
obj.say.apply(obj2,['apply',2]) //20 ‘apply' 2
obj.say.bind(obj2,'bind',3)() //20 ‘bind' 3
这是三种方法的调用方式,一目了然。call和apply是传参方式不同,bind是需要加()调用。
手写三种方式 直接上代码:
Function.prototype.bindNew = function(){
if(typeof(this) !== 'function') {
throw new Error('not a function!!');
}
// var args = Array.prototype.slice.call(arguments) //将参数拆解为数组
var args = [...new Set(arguments)] //将参数拆解为数组
var t = args.shift() //获取数组第一项
var self = this //obj.bind(...)中得obj
return function(){ //因为是bind,bind与apply和call的区别就是要调用方法 a.bing(b)()
return self.apply(t,args)
}
}
Function.prototype.callNew = function(){
if(typeof(this) !== 'function') {
throw new Error('not a function!!');
}
// var args = Array.prototype.slice.call(arguments) //将参数拆解为数组
var args = [...new Set(arguments)] //将参数拆解为数组
var t = args.shift() //获取数组第一项
return this.apply(t,args)
}
Function.prototype.applyNew = function(){
if(typeof(this) !== 'function') {
throw new Error('not a function!!');
}
// var args = Array.prototype.slice.call(arguments) //将参数拆解为数组
var args = [...arguments] //将参数拆解为数组
var t = args.shift() //获取数组第一项
var self = this //obj.bind(...)中得obj
var a = [...args]
return self.call(t,...a[0])
}
obj.say.bindNew(obj2,'bindNew',1)()
obj.say.callNew(obj2,'callNew',2)
obj.say.applyNew(obj2,['applyNew',2])