网络日志

关于call,apply,bind的用法区别

call,apply,bind三个方法都是用来改变this指向的call与appl会立刻调用函数,bind不会立刻调用函数,而是把一个函数作为返回值返回

一:call()函数,第一个参数为this即将指向的对象,第二个是可能要传的参数举个栗子

let obj1 = {
    name:"Jimmy",
    age:15,
    sayHi(){
        console.log("Nice to meet you,my name is "+this.name)
        },
    eat(food,drink){
        console.log(this.name+" like eat "+food+" "+drink)
        }
}
let obj2 = {
    name:"Harry",
    age:16
        }
obj1.sayHi.call(obj2)//Nice to meet you,my name is Harry
obj1.eat.call(obj2,"pizza","cola")//Harry like eat pizza cola

sayHi()方法的this,通过call指向了obj2eat()方法的this,通过call指向了obj2,并且传递了两个参数"pizza","cola"

二:apply函数,和call几乎一模一样,只需把"pizza","cola"两个参数以数组形式传递即可

obj1.eat.apply(obj2,["pizza","cola"])//Harry like eat pizza cola

三: bind()函数,和call也是几乎一模一样,不同的是,bind会返回一个函数,才可以使用

let fun = obj1.eat.apply(obj2,"pizza","cola")
fun()

总结:call,apply会立即执行,bind不会