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

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

  • 共同点
    都可以用来调用另一个对象的方法, 第一个参数均为提供方法的对象, 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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容