关于javascript:callapplybind的作用与用法

4次阅读

共计 738 个字符,预计需要花费 2 分钟才能阅读完成。

一、作用

  • call 和 apply 都是为了解决扭转 this 的指向。作用都是雷同的,只是传参形式不同。
  • 除了第一个参数外,call 能够接管一个参数列表,apply 只承受一个参数数组。
  • bind 和其余两个办法作用同样是可能扭转 this 指向,只是该办法会返回一个函数。并且咱们能够通过 bind 实现柯里化

二、用法示例

const steven = {
    name: 'steven',
    phoneBattery: 70,
    chargeByCall: function (level1, level2) {this.phoneBattery = level1 + level2},
    chargeByApply: function (level1, level2) {this.phoneBattery = level1 + level2},
    chargeByBind: function (level1, level2) {this.phoneBattery = level1 + level2}
}

const tom = {
    name: 'tom',
    phoneBattery: 5,
}

steven.chargeByApply.call(tom, 90, 2); // call 传参应用参数列表形式
console.log(tom.phoneBattery); // 92
steven.chargeByApply.apply(tom, [20, 50]); // apply 传参应用参数数组形式
console.log(tom.phoneBattery); // 80
const tomCharge = steven.chargeByBind.bind(tom); // bind 返回函数,调用该函数实现 this 指向扭转
tomCharge(70, 6);
console.log(tom.phoneBattery); // 76
正文完
 0