单刀直入,不多说废话啦! 首先我们创建一个机器人对象Jerry,电量为70%, charge为充电方法
const jerry = {
name: "jerry",
phoneBattery: 70,
charge: function(level) {
this.phoneBattery = level
}
}
然后给Jerry这个机器人充电到100
jerry.charge(100)
console.log(jerry) // 输出: { name: 'jerry', phoneBattery: 100, charge: [Function] }
随后再创建一个Tom机器人,在出厂时候,电量为30,但是它没有定义充电的方法,能不能使用jerry机器人的充电方法呢?当然可以啦!就是使用call方法来实现。
const tom = {
name: "tom",
phoneBattery: 30
}
jerry.charge.call(tom, 100)
console.log(tom) // 输出: { name: 'tom', phoneBattery: 100, charge: [Function] }
而apply与call的不同之处在于只接收两个参数且第二个参数为一个数组,所以我们重新定义jerry机器人对象中的charge充电方法传入两个参数
const jerry = {
name: "jerry",
phoneBattery: 70,
charge: function(level1, level1) {
this.phoneBattery = level1 + level1
}
}
const tom = {
name: "tom",
phoneBattery: 30
}
jerry.charge.apply(tom, [tom.phoneBattery, 70])
console.log(tom) // 输出: { name: 'tom', phoneBattery: 100, charge: [Function] }
最后就bind的使用啦, 会创建一个新函数, 在例子中传入Tom机器人这个对象并赋值给tomCharge,但并不是立即充电,而是要再手动执行一遍tomCharge函数哦
const jerry = {
name: "jerry",
phoneBattery: 70,
charge: function(level1, level1) {
this.phoneBattery = level1 + level1
}
}
const tom = {
name: "tom",
phoneBattery: 30
}
const tomCharge = jerry.charge.bind(tom)
tomCharge(tom.phoneBattery, 70)
console.log(tom) // 输出: { name: 'tom', phoneBattery: 100, charge: [Function] }