继承类Class与super()

class Shape {
    area: number;
    private color: string;
    constructor ( public name: string, width: number, height: number ) {
        this.area = width * height;
        this.color = "pink";
    };
    shoutout() {
        return "I'm " + this.color + " " + this.name +  " with an area of " + this.area + " cm squared.";
    }
}
 


class Shape3D extends Shape {
    volume: number;
    constructor ( public name: string, width: number, height: number, length: number ) {
        super( name, width, height );
        this.volume = length * this.area;
    };
    shoutout() {
        return "I'm " + this.name +  " with a volume of " + this.volume + " cm cube.";
    }
    superShout() {
        return super.shoutout();
    }
}
 
var cube = new Shape3D("cube", 30, 30, 30);
console.log( cube.shoutout() );
console.log( cube.superShout() );


1. 在构造函数中调用父类构造器

方法内第二行 调用了this.area  ,area存在于父类shape中,在此之前调用super()

constructor (public name: string, width: number, height: number, length: number) {
  super(name, width, height); // 调用父类 Shape 的构造函数
  this.volume = length * this.area;
}
  • 作用:确保父类 Shape 的初始化逻辑被执行(初始化 namearea 和 color

  • 必要性:子类必须在访问 this 或返回对象前调用 super()(JavaScript 的语法规则)

2. 在方法中调用父类方法

类继承后,子类可以对父类的方法重新定义,这个过程称之为方法的重写

其中 super 关键字是对父类的直接引用,该关键字可以引用父类的属性和方法。

superShout() {
  return super.shoutout(); // 调用父类 Shape 的 shoutout() 方法
}
  • 作用:直接访问父类中被覆盖(override)的方法

  • 必要性当子类重写父类方法后,仍需要复用父类原始逻辑时使用

3.shape父类中constructor 为构造器,shoutout为方法。

解释:构造器是一种特殊的函数,用于创建对象。

————————————————————————————————————————

引申内容:即使不需要父类字段,字段是类里面声明的变量。也必须先调用super(),确保整个对象继承结构正确建立(原型链连接)。并且在此处用到了父类的this.area,所以在用到前就必须执行super()。子类构造函数必须调用 super() 才能使用 this。

何时可以省略 super()

唯一例外:如果父类没有显式定义 constructor(使用默认空构造),且子类不需要初始化,可省略子类构造函数。

// 父类没有显式构造函数 → 可省略子类构造函数
class Base { /* 默认空构造 */ }
class Child extends Base { 
  // 无构造 → 隐式调用 super()
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值