call apply bind 都是用于改变函数this的指向
var cat={
name:'猫咪',
eatFish:function(fish,method){
console.log(this.name+'吃'+fish+','+method)
console.log('this指向:',this)
}
}
var dog={
name:'小狗',
eatBone:function(){
console.log('吃骨头')
}
}
call()/ apply()
有只狗和猫,猫会吃鱼,狗不会,狗想吃鱼,猫就先吃再喂给狗
这里有两种方式:call,apply,传参数方法不同,功能都是改this指向
它们都是直接执行
cat.eatFish.call(dog,'拉丁鱼','call') //改变this指向至dog,直接运行
cat.eatFish.apply(dog,['黄鱼','apply']) //以数组传参,直接运行
结果:
小狗吃拉丁鱼, this指向: {name: “小狗”, eatBone: ƒ}
小狗吃黄鱼,apply this指向: {name: “小狗”, eatBone: ƒ}
bind()
猫天天喂狗也不是个事,此时就有,建立一个方法,交给狗,这样狗就可随时吃鱼了
bind()返回一个方法,而不是直接执行
var dogEatFish=cat.eatFish.bind(dog,'各种鱼','bind') //返回一个方法
console.log(dogEatFish)
dogEatFish() //运行返回的方法
结果:
ƒ (fish,method){
console.log(this.name+‘吃’+fish+’,’+method)
console.log(‘this指向:’,this)
}
小狗吃各种鱼,bind
this指向: {name: “小狗”, eatBone: ƒ}