You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何在子类调用曾祖父类方法?name字段undefined如何解决

JavaScript类继承相关问题解答

一、曾祖父类方法调用相关问题

  • Athlete类调用TeamMate(曾祖父)的printSentence方法,你当前写的this.printSentence()是可行的:只要SoccerPlayer、TeamMate之间没有重写printSentence方法,实例的this会顺着原型链向上找到TeamMate原型上的该方法。
  • 你尝试super.printSentence未生效的原因:super在Athlete类中默认指向父类SoccerPlayer的原型,不过如果SoccerPlayer没有定义同名的printSentence方法,super.printSentence()也会继续向上查找,理论上也能调用成功,如果调用失败可以检查是否中间类重写了同名方法。
  • 在Athlete类中使用super.printPositon()是正确的调用方式:printPositon是Athlete的直接父类SoccerPlayer定义的方法,super可以直接定位到该方法。

二、运行后name字段返回undefined的原因

问题出在TeamMate类的printSentence方法实现上:

printSentence() {
  console.log(super.printName(), "is an excellent teammate!" );
}

你调用的super.printName()本身没有返回值,它内部是自己执行console.log(this.name),执行完成后默认返回undefined,你把这个返回值作为参数传给外层的console.log,自然就会打印undefined。

同时你的代码还存在另外两处隐藏问题:

  1. SoccerPlayer类的printPositon方法中直接使用了position变量,没有加this前缀,访问的是全局作用域的position,运行也会返回undefined,需要修改为this.position。
  2. 你最后调用console.log(soccerPlayer.printGreatGrandFatherMethod()),而printGreatGrandFatherMethod返回的是printSentence()的执行结果,printSentence本身没有返回值,所以这里也会额外打印一次undefined。

三、修复后的代码示例

class Person {
  constructor(name) {
    this.name = name;
  }
  // 修改printName为返回name,也可以直接在printSentence里取this.name
  printName() {
    return 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);
    this.teamMateName = teamMateName;
    this.position = position;
  }
  printPositon() {
    console.log("Positon: ", this.position);
  }
}

class Athlete extends SoccerPlayer{
  constructor(name, teamMateName, position, sport) {
    super(name, teamMateName, position);
    this.sport = sport;
  }
  printSport() {
    console.log("Favorite sport: ", this.sport);
  }
  printGreatGrandFatherMethod() {
    this.printSentence()
  }
}

const soccerPlayer = new Athlete('PLAYER1', 'Frederick', 'Defender', 'Soccer');
soccerPlayer.printGreatGrandFatherMethod(); // 输出:PLAYER1 is an excellent teammate!

内容的提问来源于stack exchange,提问作者Andres

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 03:54:07