web前端必做笔记之一:call,apply,bind基本语法
call可以调用函数,call可以改变函数中this指向
<script>
function fun(){
console.log("hello world");
};
fun.call()
</script>
<script>
function fun(){
console.log(this.name);
};
let cat = {
name:"喵喵"
}
fun.call(cat)
let dog = {
name:"旺财",
sayName(){
console.log("我是" + this.name);
}
}
dog.sayName();
dog.sayName.call(cat);
</script>
let dog = {
name:"旺财",
sayName(){
console.log("我是" + this.name);
},
eat(food){
console.log("我喜欢吃" + food)
}
}
dog.eat("骨头");
dog.eat.call(cat);
dog.eat.call(cat,"鱼");
let dog = {
name:"旺财",
sayName(){
console.log("我是" + this.name);
},
eat(food1,food2){
console.log("我喜欢吃" + food1 + food2)
}
}
dog.eat.call(cat,"鱼","肉");
</script>
<script>
dog.eat.apply(cat,["鱼","肉"]);
dog.eat.bind(cat,"鱼","肉");
let fun = dog.eat.bind(cat,"鱼","肉");
fun();
</script>
call,apply,bind基本语法总结:
1.call和apply会调用函数,可以改变函数中this指向
区别在于:传参的方式不同
2.call和bind,传参的方式完全一样
区别在于:call会直接调用,而bind它会作为一个返回值返回一个函数然后
才能够调用。
|