call、apply、bind的基本概念
call、apply、bind
call是一个方法,是函数的方法
function fun(){
console.log("hello world")
}
call可以调用函数
fun.call() // hello world
call可以改变函数中this的指向
function fun(){
console.log(this)
}
let cat = {
name: "喵喵"
}
fun.call(cat) // 喵喵
let dog = {
name: "旺财",
sayName(){
console.log("我是"+this.name)
},
eat(food1, food2){
console.log("我喜欢吃"+food1+food2)
}
}
dog.sayName.call(cat) // 我是喵喵
dog.eat.call(cat,"鱼","肉") // 我喜欢吃鱼肉
dog.eat.apply(cat,["鱼","肉"]) // 我喜欢吃鱼肉
let fun = dog.eat.call(cat,"鱼","肉")
fun() // 我喜欢吃鱼肉
浙公网安备 33010602011771号