JS apply(),call(),bind() 的使用与区别

2021-06-24  本文已影响0人  Jachin_927

定义: 当前对象通过该函数,能够调用另一个对象的方法

用法

const person = {
  firstName: "John",
  lastName: "Steven",
  fullName: function() {
    console.log(this.firstName + " " + this.lastName)
  }
}

const person1 = {
    firstName: "Bill",
    lastName: "Gates",
}

person.fullName.apply(person1);
// Bill Gates

const num = [1, 4, 3, 8, 7, -3, -5];

const maxNum = Math.max.apply(this, num);
// 8
const minNum = Math.min.apply(this, num[0], num[1], num[2], num[3], num[4], num[5]);
// 错误, apply()第二个参数需为数组
const person = {
  firstName: "John",
  lastName: "Steven",
  fullName: function() {
    console.log(this.firstName + " " + this.lastName)
  }
}

const person1 = {
    firstName: "Bill",
    lastName: "Gates",
}

person.fullName.call(person1);
// Bill Gates

const num = [1, 4, 3, 8, 7, -3, -5];

const maxNum = Math.max.call(this, num);
// NaN
const minNum = Math.min.call(this, num[0], num[1], num[2], num[3], num[4], num[5]);
// -5
this.num = 10;
const person = {
  num: 20,
  getNumber: function () {
    return this.num;
  }
}

console.log(person.getNumber());
// 20 
// this 指向 person

const personA = person.getNumber;
console.log(personA());
// 10
// this 指向全局

const personB = {
  num: 30
}
const personC = personA.bind(personB);
console.log(personC());
// 30
// this 指向 peronB
上一篇 下一篇

猜你喜欢

热点阅读