class Person {
constructor(name, age){
this.name = name;
this.age = age;
}
toString(address, todo){
return `${this.name}的年龄是${this.age}, 来自${address}, 喜欢${todo}`
}
}
let person = new Person('小王', 27);
console.log(person.name); //小王
console.log(person.toString('大连', '冲浪')); //小王的年龄是27, 来自大连, 喜欢冲浪
let personT = {
name: '小米',
age: 13
}
console.log(person.toString.call(personT, '北京', '唱歌')); //小米的年龄是13, 来自北京, 喜欢唱歌
console.log(person.toString.apply(personT, ['上海', '旅游'])); //小米的年龄是13, 来自上海, 喜欢旅游
console.log(person.toString.bind(personT, '南京', '弹钢琴')()); //小米的年龄是13, 来自南京, 喜欢弹钢琴
从例子中可以看出,call(), apply(), bind() 是用来重新定义 this 的。
三者的共同点为第一个参数为需要重定义的this对象。
三者的区别为:
- call()的参数为多个,参数之间使用 ‘,’ 分隔;
- apply()的参数为两个,第二个参数为数组,需传递的元素均放在数组中进行传递,第一个与第二个参数使用‘,’分隔;
- bind()的参数规则与call()相同,但与call()和apply()不同的是,call()和apply()均可直接执行,而bind()则生成一个新的函数,需在其后添加()才可执行;