我想從曾祖父那里呼叫一個方法到 Athlete 類,
我怎樣才能做到這一點?
我嘗試使用 super.printSentence 但這沒有用,
這是在 Athlete 類中呼叫 super.printPositon() 方法的正確方法嗎?
關于如何呼叫這個 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());
為什么我的名稱欄位未定義?
uj5u.com熱心網友回復:
只為了 this.printSentence()
在繼承(原型與否)中,this可以訪問所有方法。
除非您使用這樣的私有方法:
class ClassWithPrivateMethod {
#privateMethod() {
return 'hello world';
}
}
如果你考慮一下,如果 aPerson有一個name繼承自的任何類也Person將有一個成員name。對于繼承自 的類的任何實體也是如此Person。例如:
const soccerPlayer = new SoccerPlayer('PLAYER1', 'MATE NAME', '1');
console.log(soccerPlayer.name); // Prints `PLAYER1`
uj5u.com熱心網友回復:
printSentence()不回傳值,所以return this.printSentence()會回傳undefined。由于那是printGreatGrandFatherMethod回傳的內容,因此console.log(soccerPlayer.printGreatGrandFatherMethod());將 log undefined。
同樣的printName()情況也不回傳值,因此console.log(super.printName())將記錄undefined
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/340782.html
標籤:javascript
