call/apply/bind 用法

用法 call/apply/bind

call

函数通过call调用时,函数体内的this指向call方法传入的第一个实参,而call方法后续的实参会依次传入作为原函数的实参传入。

function setDetails(name,color){
                this.name=name;
                this.color=color;
              }
    let cat1={};
    let cat2={};
    setDetails.call(cat1,'大毛','橘色')
    setDetails.call(cat2,'二毛','黑色')
    console.log(cat1.name)//大毛
    console.log(cat2.name)//二毛
let person1 ={
  name:'zs',
  say:function (hobby) {
    console.log(this.name);
    console.log('爱好:'+ hobby);
  }
}
let person2 = {
  name:'ls'
}
person1.say('打游戏')
person1.say.call(person2,'健身')

apply

apply与call功能一致,但是在调用方式上,是将剩余的实参以一个数组的方式传参:

function setDetails(name,color){
                this.name=name;
                this.color=color;
              }
    let cat1={};
    let cat2={};
    setDetails.apply(cat1,['大毛','橘色'])
    setDetails.apply(cat2,['二毛','黑色'])
    console.log(cat1.name)//大毛
    console.log(cat2.name)//二毛

bind

bindcallapply的功能相似,但有不同,bind不会立即调用函数,只做this的绑定,并且返回一个新的函数,
这个函数运行的逻辑与原函数一致,但是this会指向之前绑定的对象。

function setDetails(name,color){
  this.name = name
  this.color = color
}
let cat1 = {}
let setDetails2 = setDetails.bind(cat1)  //新函数this指向cat1
setDetails2('大毛','橘色')
原文地址:https://www.cnblogs.com/xm0328/p/13977079.html