TypeScript 继承
最后,我们可以继承一个已存在的类并创建一个派生类,继承使用关键字 extends。
接下来我们在 class.ts 文件末尾添加以下代码,如下所示:
- 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() );
派生类 Shape3D 说明:
- Shape3D 继承了 Shape 类, 也继承了 Shape 类的 color 属性。
- 构造函数中,super 方法调用了基类 Shape 的构造函数 Shape,传递了参数 name, width, 和 height 值。 继承允许我们复用 Shape 类的代码,所以我们可以通过继承 area 属性来计算 this.volume。
- Shape3D 的 shoutout() 方法重写基类的实现。superShout() 方法通过使用 super 关键字直接返回了基类的 shoutout() 方法。 其他的代码我们可以通过自己的需求来完成自己想要的功能。

转载本站内容时,请务必注明来自W3xue,违者必究。