首先我們要明白bind,apply和call的區(qū)別
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 ‘a(chǎn)pply' 2
obj.say.bind(obj2,'bind',3)() //20 ‘bind' 3
這是三種方法的調(diào)用方式,一目了然凿傅。call和apply是傳參方式不同呻率,bind是需要加()調(diào)用。
手寫三種方式 直接上代碼:
Function.prototype.bindNew = function(){
if(typeof(this) !== 'function') {
throw new Error('not a function!!');
}
// var args = Array.prototype.slice.call(arguments) //將參數(shù)拆解為數(shù)組
var args = [...new Set(arguments)] //將參數(shù)拆解為數(shù)組
var t = args.shift() //獲取數(shù)組第一項(xiàng)
var self = this //obj.bind(...)中得obj
return function(){ //因?yàn)槭莃ind,bind與apply和call的區(qū)別就是要調(diào)用方法 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) //將參數(shù)拆解為數(shù)組
var args = [...new Set(arguments)] //將參數(shù)拆解為數(shù)組
var t = args.shift() //獲取數(shù)組第一項(xiàng)
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) //將參數(shù)拆解為數(shù)組
var args = [...arguments] //將參數(shù)拆解為數(shù)組
var t = args.shift() //獲取數(shù)組第一項(xiàng)
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])