一、作用
- 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);
console.log(tom.phoneBattery);
steven.chargeByApply.apply(tom, [20, 50]);
console.log(tom.phoneBattery);
const tomCharge = steven.chargeByBind.bind(tom);
tomCharge(70, 6);
console.log(tom.phoneBattery);