TypeScript 继承

TypeScript 允许继承一个已存在的类并创建一个派生类

继承使用关键字 extends

创建文件 class.ts 并输入以下内容

class Shape
{

    area: number;
    color: string;
    width:number;
    height:number;

    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. Shape3D 继承了 Shape 类, 也继承了 Shape 类的 color 属性

  2. 构造函数中,super 方法调用了基类 Shape 的构造函数 Shape,传递了参数 name, width, 和 height 值

  3. 继承允许我们复用 Shape 类的代码,所以我们可以通过继承 area 属性来计算 this.volume

  4. Shape3D 的 shoutout() 方法重写基类的实现

    superShout() 方法通过使用 super 关键字直接返回了基类的 shoutout() 方法

运行以上代码,浏览器控制台输出信息如下

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.