简述call、apply、bind的区别
call
<script type="text/javascript">
function xiaohong(){
alert("小红");
}
function xiaoming(){
return "小明";
}
//xiaohong();
xiaohong.call(xiaoming)
</script>
解析:上述函数中“xiaohong.call(xiaoming)”表示xiaohong()函数里的this对象,指向了xiaoming()里的对象,但是函数调用依旧是xiaohong()
<script type="text/javascript">
var Dog = function(){
this.name="汪星人";
this.shout = function(){
alert(this.name);
}
};
var Cat = function(){
this.name="喵星人";
};
var dog= new Dog();
var cat=new Cat();
dog.shout(); //"汪星人"
//若想Cat含有shout方法,即可需要call()
dog.shout().call(cat); //dog.shout中的this对象,将指向cat对象
</script>
解析:dog.shout().call(cat)的this不再指向dog,而是变成了cat,所以console出的name为cat中的"喵星人"
apply
<script type="text/javascript">
var xh={
name:"小红",
job:"JS工程师"
};
var xm={
name:"小明",
job:"资深前端开发工程师"
};
var jx={
name:"杰西",
job:"前端开发总监"
};
function myjob(gender,age,company){
alert(this.name+gender+"今年"+age+"岁,在"+company+"担任"+this.job +"一职");
}
myjob.call(xh,'女',22,"腾讯");
myjob.call(xm,'男',23,"京东");
myjob.apply(xh,['女',22,"腾讯"]);
myjob.apply(xm,['男',23,'京东']);
</script>
call() VS apply()总结:
(1)在call()传入参数的时候,需要与函数所接受的参数一一对应
(2)在apply()传入参数的时候,则必须以“数组”的方式传入,数组中的元素,需要与函数所接受的参数一一对应
bind
<script type="text/javascipt">
var info=["W3C","QQ","Sina","Sohu"];
var it ={
info:["前端开发网","腾讯","新浪","搜狐"],
getInfo: function(){
alert(this.info.join(","));
}
};
//it.getInfo();
var data=it.getInfo;
data(); //this指向windows对象,"W3C,QQ,Sina,Sohu"
//若需要弹出中文it中的内容,需要bind()函数
var data1 = it.getInfo.bind(it);
data(); //this指向it中的对象,即中文内容
</script>
总结:call、apply、bind都是可以绑架“this”,逼迫this指向其他对象,改变this对象至想要指向对象。