call、apply、bind的基本概念
call是一个方法,是函数的方法
call可以调用函数,改变函数中this的指向
function fun(){
console.log("hello world")
};
fun.call();
call挨个传参,不需要使用数组
apply需要用数组传参
bind不会调用函数,只能作为返回值返回一个函数
let dog = {
name: "旺财",
sayName(){
console.log("我是"+this.name)
},
eat(food1,food2){
console.log("我喜欢吃"+food1+food2)
}
}
let cat = {
name: "喵喵"
}
dog.sayName();//我是旺财
dog.sayName.call(cat);//我是喵喵
dog.eat.call(cat);//我喜欢吃undefinedundefined,因为只改变了对象,没有传参
dog.eat.call(cat,"鱼","肉");//假如传两个参数的话,挨个传
dog.eat.apply(cat,["鱼","肉"])//apply需要用数组传参
let fun2 = dog.eat.bind(cat,"鱼","肉")//bind不会调用函数,只能作为返回值返回一个函数
fun2();//我喜欢吃鱼肉
call、apply、bind的实际应用
继承:子类可以使用父类的方法
call的好处,实现多重继承
function Animal(){
//this指向小cat
this.eat = function(){
console.log("吃东西")
}
}
function Bird(){
this.fly = function(){
console.log("我会飞")
}
}
function Cat(){
//调用animal函数,这里的this指向小cat,
Animal.call(this);
//验证this指向的是小cat
this.sayName = function(){
console.log("输出自己的名字")
}
//多重继承,Bird里面的this指向小cat
Bird.call(this);
}
let cat = new Cat();//创建对象,this就指向创建的cat
cat.eat(); //吃东西
cat.sayName(); //输出自己的名字
cat.fly(); //我会飞