引言
声明:本文章来源与bilibili up主:晓舟报告
call
call、apply、bind三个方法,学会一个,其他两个便也很容易明白。
call是一个方法,函数的方法。
1.call 可以调用函数
function func(){
console.log("hello world")
};
func.call();//输出 hello world
2.call可以改变函数中this的指向
example 1:
function func(){
console.log(this);
};
func.call();// window对象
function fun(){
console.log(this.name);
};
let cat = {
name:"喵喵"
}
fun.call(cat);// 喵喵
上述代码说明,fun函数中的this的指向cat
example 2:
let dog = {
name:"旺财",
sayName(){
console.log("我是"+this.name);
},
eat(food1,food2){
console.log("我喜欢吃"+food1+food2)
}
}
let cat = {
name:"喵喵"
}
dog.eat("骨头");// 我喜欢吃骨头
dog.eat.call(cat);//我喜欢吃undefined
dog.eat.call(cat,"鱼","肉");//我喜欢吃鱼肉
通过 expmple 2中的代码可以说明,call的第一个参数是函数中this指向的对象,而往后的参数就是要给函数传的参数。
apply
apply函数与call函数非常相似,唯一的区别是传参不一样。
使用apply函数想要传参时需要通过数组的方式,代码如下。
let dog = {
name:"旺财",
sayName(){
console.log("我是"+this.name);
},
eat(food1,food2){
console.log("我喜欢吃"+food1+food2)
}
}
let cat = {
name:"喵喵"
}
dog.eat.apply(cat,["鱼","肉"]);//我喜欢吃鱼肉
bind方法
bind方法与call方法传参的方式一模一样,不同之处在于bind方法不会直接调用,会将函数作为一个返回值返回。代码如下:
let dog = {
name:"旺财",
sayName(){
console.log("我是"+this.name);
},
eat(food1,food2){
console.log("我喜欢吃"+food1+food2)
}
}
let cat = {
name:"喵喵"
}
let fun = dog.eat.bind(cat,"鱼","肉");//我喜欢吃鱼肉
fun();//我喜欢吃鱼肉