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
的初始化逻辑被执行(初始化name
、area
和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() }