相同点:
1、都用来改变this对象的指向。
2、第一个参数都是this要指向的对象。
3、都可以利用后续参数进行传参。
不同点:
1、(调用方式)call、apply都是对函数的直接调用,而bind返回的是函数,需要再次调用,所以写法上就有了区别。
var huoche ={
name:"火车",
say:function(){
alert(this.name+"呜呜呜呜!");
}
}
var feiji={
name:"飞机",
say:function(){
alert(this.name+"轰轰轰轰!");
}
}
feiji.say();//飞机轰轰轰轰!
//call
feiji.say.call(huoche);//火车轰轰轰轰!
//apply
feiji.say.apply(huoche);//火车轰轰轰轰!
//bind
feiji.say.bind(huoche)();//火车轰轰轰轰! 返回的是方法,需要再次调用。
2、(传参方式)call和bind传参的参数应和调用方法参数一致,而apply以数组方式传参,数组中的元素应和调用方法的参数一致。
var huoche ={
name:"火车"
}
var feiji={
name:"飞机",
say:function(a,b){
alert(this.name+a+b);
}
}
feiji.say("hello","world");//飞机helloworld
//call
feiji.say.call(huoche,"hello","world");//火车helloworld
//bind
feiji.say.bind(huoche)("hello","world");//火车helloworld
//apply
feiji.say.apply(huoche,["hello","world"]);//火车helloworld apply以数组方式传参