对象中的apply&call

显式绑定法 apply/call(); 通过显式绑定法可以使用另一个对象中的方法

  • apply/call()都是JS预定义的方法, 他们都可以用于将一个对象作为参数调用对象方法
  • FOR example
const person1 = {
  nameFunction: function() {
    return this.name + this.sex + this.age + '岁';
  },
};
const person2 = {
  age: 20,
  sex: '女',
  name: 'Alone'
};
person1.nameFunction.call(person2);// 把函数nameFunction的this指向替换成person2;

call(); 除了可以把对象当参数传过去外, 还能带其他的参数, 形式call(Obj, ...arr);

  • 使用方法
const personClass = {
  name: 'Steve Jobs',
  age: 65,
  sex: '男',
};
const personFun = {
  SpeakFunc: function(a,b,c) {
    return `姓名${this.name},性别${this.sex},${this.age}岁,${a+b+c}`
  }
};
personFun.SpeakFunc.call(personClass, '爱好', 'Mac', '电脑');
const hello = 'hello';
const Mac = 'Mac';
const Yo = 'Yo';
personFun.SpeakFunc.call(personClass, {hello}, {Mac}, {Yo});

apply()

  • 基本和call()一样, 区别传参形式不一样, call()分别接收参数, apply()接收数组参数;
  • 实用方法example: Math.max('1','2','3'); => 分别接收参数,如果是一个数组需要取最大值那么用apply
  • Math.max.apply(null, [1,3,4,5,6]); => 6;
  • 使用方法
const person = {
  interest: '玩球',
  color: 'black',
  house: '太空站',
  sex: '男'
};
const interest = '唱歌',
      color = 'blue',
      house = '火星',
      sex = '女';
let personFun = {
  interest: '唱歌',
  color: 'blue',
  house: '火星',
  sex: '女',
  example: (a, b, c) => {
    // 箭头函数this的指向始终表示定义箭头函数的对象=>window or '其他'
    return `这个${this.sex}人在${this.house}${this.interest}${a}${b}${c}`
  }
};
personFun.example.apply(person, ['好玩','bu','好玩']); 
//'这个undefined人在undefinedundefined好玩bu好玩' 
// Remark对像函数里面不能写箭头函数
// 改成
let personFun = {
  example: function(a, b, c){
    return `这个${this.sex}人在${this.house}${this.interest}${a}${b}${c}`
  }
};
posted @ 2022-01-13 16:11  lutwelve  阅读(54)  评论(0)    收藏  举报