<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>call,apply,bind的区别</title>
</head>
<body>
<H1>你好</H1>
<script>
//1
// //call是一个方法,可以调用函数的方法
// function fun(){
// console.log(this)//this指向windows
// console.log('hello')
// }
// fun.call(); //call直接调用了fun函数
// 2 改变this的指向
function fun(){
console.log(this.name) //this指向windows
}
let cat={
name:'mm'
}
fun.call(cat) //call调用函数'fun',并且把cat传进来,此时this.name===cat.name
let dog={
name:"旺财",
sayName(){
console.log("我是"+this.name);
},
eat(food){
console.log('我喜欢吃'+food)
}
}
dog.sayName();//我是旺财
dog.sayName.call(cat) //我是mm,相当于call调用了函数sayname整个函数,把cat传进去了,this指向了cat
dog.eat('骨头') //我喜欢吃骨头
dog.eat.call(cat) //我喜欢吃undefined,需要传参
dog.eat.call(cat,'鱼') //我喜欢吃鱼
//3 apply 与call唯一的区别就是传参不一样,apply是通过数组传参
dog.eat.call(cat,['鱼']) //我喜欢吃鱼
//bind 传参和call一模一样,但是bind()方法不回调用函数
let fun=dog.eat.call(cat,'鱼');
fun();
</script>
</body>
</html>