提问人: 提问时间:7/17/2022 更新时间:7/17/2022 访问量:629
访问父类的属性时,“this”和“super”之间有什么区别吗?
Is there any differences between "this" and "super" when accessing parent class' property?
问:
我一直认为“super”是访问父类属性的唯一方法,但我意识到“this”也可以访问父类的属性。在这种情况下,“super”和“this”有什么区别吗?
class Human {
constructor (name, age) {
this.name = name;
this.age = age;
}
mouse (sentense) {
console.log(`${this.name}: "${sentense}".`);
}
}
class Footballer extends Human {
constructor(name, age, position, team) {
super(name, age);
this.team = team;
this.position = position;
}
talk (sentense) {
super.mouse(sentense); // This works.
this.mouse(sentense); // This also works.
}
}
答:
2赞
CertainPerformance
7/17/2022
#1
如果使用 ,引擎将首先尝试访问实例本身的属性。如果它在实例上不存在,它将转到原型 ()。如果它不存在,它将转到查看该属性是否存在。this
Footballer.prototype
Human.prototype
如果使用 ,它将立即转到父类 ,以查看该属性是否存在,并从那里向上(而不是先遍历实例和子原型)。super
Human.prototype
如果父级和子级上都存在同名的方法,这一点尤其重要,这并不少见。
class Human {
mouse () {
console.log('parent class');
}
}
class Footballer extends Human {
mouse() {
console.log('child class');
}
talk () {
super.mouse();
this.mouse();
}
}
const f = new Footballer();
f.talk();
评论
0赞
7/17/2022
非常感谢您的帮助!我学到了很多东西! 👍
0赞
Tushar Shahi
7/17/2022
#2
有很大的不同。
在 Java 和 Javascript 等语言中,
您可以使用父级的属性和方法。super
您正在访问孩子的属性和方法。this
this.mouse()
之所以有效,是因为首先为子项 (Footballer) 访问该属性,而当未找到该属性时,将在父项 (Human) 中查找该属性。这就是继承的工作原理。当访问一个名为 的属性时,Javascript 将尝试在原型链中向上移动,直到找到一个名为 的属性。mouse
x
x
如果你像 Footballer 一样定义一个属性,那么不会起作用,但会起作用,证明差异。kick
super.kick()
this.kick()
class Human {
constructor (name, age) {
this.name = name;
this.age = age;
}
mouse (sentense) {
console.log(`${this.name}: "${sentense}".`);
}
}
class Footballer extends Human {
constructor(name, age, position, team) {
super(name, age);
this.team = team;
this.position = position;
}
kick(){
console.log("kicked");
}
play(){
this.kick();
super.kick();
}
talk (sentense) {
super.mouse(sentense); // This works.
this.mouse(sentense); // This also works.
}
}
const messi = new Footballer();
messi.play();
评论
0赞
7/17/2022
非常感谢您的帮助!我学到了很多东西! 😭
评论