函数中使用
bind
javascript">function eat(food,name){
this.food=food
this.call=call
}
function weather(food,name,what){
console.log("今天的天气是"+what);
console.log("我喜欢吃"+food);
console.log("我是"+name)
}
weather.bind(eat,"肉","狗","大雨")()
call
javascript">function eat(food,name){
this.food=food
this.call=call
}
function weather(food,name,what){
console.log("今天的天气是"+what);
console.log("我喜欢吃"+food);
console.log("我是"+name)
}
weather.call(eat,"肉","狗","大雨")
apply
javascript">function eat(food,name){
this.food=food
this.call=call
}
function weather(food,name,what){
console.log("今天的天气是"+what);
console.log("我喜欢吃"+food);
console.log("我是"+name)
}
weather.apply(eat,["肉","狗","大雨"])
javascript">function eat(food,name){
this.food=food
this.call=call
}
function weather(food,name,what){
console.log("今天的天气是"+what);
console.log("我喜欢吃"+food);
console.log("我是"+name)
}
weather.bind(eat,"肉","狗","大雨")()
weather.call(eat,"肉","狗","大雨")
weather.apply(eat,["肉","狗","大雨"])
在构造函数中使用
apply
javascript">function student(name,age) {
this.name=name
this.age=age
}
function person(name,age,grade) {
this.grade=grade
student.apply(this,arguments)
}
const a=new person("小明",18,"五年级")
console.log("姓名--"+a.name);
console.log("年龄--"+a.age);
console.log("年级--"+a.grade);
但是用apply参数数组必须一致
call
javascript">function student(name,age) {
this.name=name
this.age=age
}
function person(name,age,grade) {
this.grade=grade
student.call(this,name,age)
}
const a=new person("小明",18,"五年级")
console.log("姓名--"+a.name);
console.log("年龄--"+a.age);
console.log("年级--"+a.grade);
bind
javascript">function student(name,age) {
this.name=name
this.age=age
}
function person(name,age,grade) {
this.grade=grade
student.bind(this,name,age)()
}
const a=new person("小明",18,"五年级")
console.log("姓名--"+a.name);
console.log("年龄--"+a.age);
console.log("年级--"+a.grade);
三者区别
虽然他们的作用都是改变this的指向,第一个参数都是你要改变的this的指向但是他们也有很b多不同点
1.call和apply是立即执行的
2.bind返回的是一个函数
3.apply的第二个参数是一个数组、
4.call除了第一个参数都是传入的参数
bind和call的方法传参方式一样但是返回的是函数想要执行必须以函数的方式执行