在JavaScript中,call
、apply
和bind
是Function
对象自带的三个方法,都是为了改变函数体内部 this
的指向。
apply 、 call 、bind
三者第一个参数都是 this
要指向的对象,也就是想指定的上下文;
apply 、 call 、bind
三者都可以利用后续参数传参;
bind 是返回对应 函数,便于稍后调用;apply 、call
则是立即调用 。
bind 是为函数绑定新的this,可以永久绑定:
<script>
var person={
name:"路人甲"
}
let fun = {
name:"路人乙",
showname(){
console.log( this.name );
}
}
fun.showname(); //路人乙
let f = fun.showname;
f.bind(person)(); //路人甲
永久绑定方法如下:
fun.showname = fun.showname.bind(person);
fun.showname(); //路人甲
</script>
也可以传递默认参数,
var person={
name:"路人甲"
}
let fun = {
name:"路人乙",
showname(){
let arr = [...arguments];
console.log( `传递参数为:${arr}<==========>${this.name}` );
}
}
fun.showname(1,2,3); //传递参数为:1,2,3<==========>路人乙
fun.showname.bind(person,100)(1,2,3); //传递参数为:100,1,2,3<==========>路人甲
2.对于 apply、call 二者而言,作用完全一样,是临时调用;只是接受 参数 的方式不太一样。call 是把参数按顺序传递进去,而 apply 则是把参数放在数组里。