美文网首页
JS apply(),call(),bind() 的使用与区别

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

作者: Jachin_927 | 来源:发表于2021-06-24 18:47 被阅读0次

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

  • 共同点
    都可以用来调用另一个对象的方法, 第一个参数均为提供方法的对象, this 会被指定为当前调用对象

  • 不同点
    apply() : 只能有两个参数, 且第二个参数需为数组
    call() : 可以有多个参数
    bind() : 参数用法类似于 call(),但 call/apply 是立刻调用函数的,bind 是返回一个函数,可以在其他时候调用。

用法

  • apply()
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()第二个参数需为数组
  • call()
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
  • bind()
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

相关文章

网友评论

      本文标题:JS apply(),call(),bind() 的使用与区别

      本文链接:https://www.haomeiwen.com/subject/qwvcsltx.html