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

TypeScript子类中super.role与this.role能否区分?为何super.role返回undefined?

问题解答

核心结论

你不能通过super.role这种方式直接访问父类的同名实例属性,这是JavaScript/TypeScript的继承机制导致的,所以super.role返回undefined是预期行为。

原因分析

  1. 实例属性的存储机制:

    • 父类Person中的role是实例属性,它被直接挂载在实例对象(this)上,而非父类的原型(Person.prototype)上。
    • 子类User声明了同名的role实例属性,这会在子类实例上重新定义该属性,相当于遮蔽了父类的同名实例属性。
  2. super的作用范围:

    • super在子类中主要用于访问父类的原型方法,而非实例属性。当你调用super.role时,JavaScript会去父类的原型上查找role属性,但父类原型上并没有这个属性(role是构造函数中赋值给this的实例属性),因此返回undefined。
  3. 结合你的代码流程拆解:

    • 执行super(name)时,父类构造函数会给当前User实例的this.role赋值为'parent'。
    • 紧接着子类构造函数执行this.role = 'son',覆盖了实例上的role值。
    • 此时this.role指向子类赋值的'son',而super.role因找不到父类原型上的对应属性,返回undefined。

正确处理方式

如果需要区分父类和子类的role值,可通过以下两种方式实现:

方式1:父类用私有字段存储原始值

class Person {
  private _role: string;
  role: string;
  constructor(public name: string){
    this._role = 'parent';
    this.role = this._role;
  }
  getParentRole(): string {
    return this._role;
  }
}

class User extends Person{
  role: string;
  constructor(public name: string, public userId: string){
    super(name);
    this.role = 'son';
    console.log(this.role, super.getParentRole()); // 输出 'son' 'parent'
  }
}

方式2:子类使用不同属性名区分

class User extends Person{
  userRole: string;
  constructor(public name: string, public userId: string){
    super(name);
    this.userRole = 'son';
    console.log(this.role, this.userRole); // 输出 'parent' 'son'
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:42:10