我如何在Javascript中调用曾祖父的方法?



我想调用一个从曾祖父到Athlete类的方法,

我该怎么做呢?

我试过使用super。printSentence但是没有成功,

在Athlete类中调用super. printposition()方法是正确的吗?

关于如何调用这个printSentence方法有什么建议吗?

class Person {
constructor(name) {
this.name = name;
}
printName() {
console.log(this.name);
}
}
class TeamMate extends Person {
constructor(name) {
super(name);
}
printSentence() {
console.log(super.printName(), "is an excellent teammate!" );
}
}

class SoccerPlayer extends TeamMate {
constructor(name, teamMateName, position) {
super(name, teamMateName);
this.teamMateName = teamMateName;
this.position = position;
}
printPositon() {
console.log("Positon: ", position);
}
}

class Athlete extends SoccerPlayer{
constructor(name, teamMateName, position, sport) {
super(name, teamMateName, position);
this.sport = sport;
}
printSport() {
console.log("Favorite sport: ", this.sport);
}
//If Athlete class extends from SoccerPlayer and SoccerPlayer extends from 
// the TeamMate class, how can I invoke the printSentence method 
// from the TeamMate class in this current Athlete class?
printGreatGrandFatherMethod() {
return this.printSentence()
}
}
const soccerPlayer = new Athlete('PLAYER1', 'Frederick', 'Defender', 'Soccer');
console.log(soccerPlayer.printGreatGrandFatherMethod());

为什么我得到未定义的名称字段?

Just tothis.printSentence()

在继承(无论是否为原型)中,this可以访问所有的方法。

除非你使用这样的私有方法:

class ClassWithPrivateMethod {
#privateMethod() {
return 'hello world';
}
}

如果你考虑一下,如果一个Person有一个name,任何从Person继承的类也会有一个成员name。这也适用于从Person继承的类的任何实例。例如:

const soccerPlayer = new SoccerPlayer('PLAYER1', 'MATE NAME', '1');
console.log(soccerPlayer.name); // Prints `PLAYER1`

printSentence()不返回值,因此return this.printSentence()将返回undefined。由于这是printGreatGrandFatherMethod返回的结果,因此console.log(soccerPlayer.printGreatGrandFatherMethod());将记录undefined

同样的printName()也不返回值,因此console.log(super.printName())将记录undefined

相关内容

最新更新