<!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>Document</title>
</head>
<body>
<script>
//一.call是一个方法,是函数的方法,call可以调用函数,call可以改变函数中this
function fun() {
console.log(this);
};
let phone = {
name: '小米'
}
fun.call(phone) //Object { name: "小米" }
fun() //window call只是暂时修改fun的指向
// 二.call,apply和bind的基本语法
let cat = {
name: '喵喵'
}
let dog = {
name: '旺财',
sayName() {
console.log("我是" + this.name);
},
eat(food, food1) {
console.log("我喜欢吃" + food + food1);
}
}
dog.eat.call(cat, "鱼call", "肉"); //call传参方法,第一个是要改变成的对象值,后面的是函数的参数,如题是eat(food,food1)的参数
dog.eat.apply(cat, ["鱼apply", "肉"]); //apply和call差不多,就传参方法不同
let blndFun = dog.eat.bind(cat, "鱼bind", "肉"); //bind和他们也差不多,就是不会调用函数,会返回一个值
blndFun();
</script>
</body>
</html>
运行结果: