js 函数.call调用和直接调用的区别
区别
.call调用会修改函数中this的指向
let person1 = {
name: "张三",
age: 11,
print() {
console.log(this, '====当前指针')
console.log(this.name, "===姓名");
console.log(this.age, "===年龄");
}
}
let person2 = {
print() {
console.log(this, '====当前指针')
console.log(this.name, "===姓名");
console.log(this.age, "===年龄");
}
}
let person3 = {
name: '李四',
age: 99,
}
export class CallTest {
constructor() {
}
test = function () {
person1.print();
person2.print();
person2.print.call(person1);
person1.print.call(person3);
}
}
以上代码存在2个类,person1类中存在name和age属性,person2中不存在。当他们都调用print函数时。结果如下
1.person1.print()和persion2.print()函数中的this指针都指向其本身。但是persion2.print.call(persion1)调用时,persion2.print()函数中的this指向了persion1而不是persion2。
2.入上述代码,persion3中并没有print()方法,但是我又想将信息打印出来。正常的做法是在persion3类中新增print()方法。使用.call可以将persion3中的信息打印出来,算是一种变相继承。