Typescript 快速上手学习系列 —— 继承

typescript继承

继承使用关键字 extends

实例

index.html 文件:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8"> 
	<title>typescript demo</title>
</head>
<body>
 	<script src="hello.js"></script>
</body>
</html>

修改 hello.ts 文件:

class Rectangle {
    area: number;
    private color: string;

    constructor (public name: string, width: number, height: number){
    	this.area = width * height
    	this.color = 'red';
    }

    sayHi() {
    	console.log('this.color',this.color)
        return 'I am ' + this.name  + ' the color is '+ this.color + ' the area is ' + this.area + ' cm squares.'
    }
}
var rec = new Rectangle('suq',50,60); 
console.log('rec.sayHi()', rec.sayHi());
console.log('rec.area', rec.area);
console.log('rec.name', rec.name);
console.log('rec.width', rec.width);
console.log('rec.height', rec.height);
console.log('rec.color', rec.color);
class Rectg extends Rectangle {
    volume: number;

    constructor (public name: string, width: number, height: number, length: number){
    	super(name,width,height);
    	this.volume = length * this.area
    }
    
    sayHi() {
        return 'I am ' + this.name  + ' the volume is '+ this.volume + ' cm cube.'
    }

    sayHello() {
    	return super.sayHi()
    }
}
var cuba = new Rectg('cuba',50,60,30); 
console.log('cuba.sayHi()', cuba.sayHi());
console.log('cuba.sayHello()', cuba.sayHello());

接下来,打开命令行,使用 tsc 命令编译 hello.ts 文件:

$ tsc hello.ts

编译结果:

hello.ts:19:30 - error TS2339: Property 'width' does not exist on type 'Rectangle'.

19 console.log('rec.width', rec.width);
                                ~~~~~

hello.ts:20:31 - error TS2339: Property 'height' does not exist on type 'Rectangle'.

20 console.log('rec.height', rec.height);
                                 ~~~~~~

hello.ts:21:30 - error TS2341: Property 'color' is private and only accessible within class 'Rectangle'.

21 console.log('rec.color', rec.color);
                                ~~~~~


Found 3 errors in the same file, starting at: hello.ts:19

然后,打开 index.html,可以看到如下打印信息:
请添加图片描述

派生类Rectg说明:

  • 派生类Rectg继承了Rectangle类,也继承了Rectangle类的color属性
  • 构造函数中,super 方法调用了 基类 Rectangle 的构造函数,传递了参数 name, width, 和 height 值。 继承允许复用 Rectangle 类的代码,所以可以通过继承 area 属性来计算 this.volume
  • RectgsayHello() 方法重写基类的实现。
    sayHi() 方法通过使用 super 关键字直接返回了基类的 sayHi() 方法。

参考文档:

https://www.runoob.com/w3cnote/getting-started-with-typescript.html
https://www.runoob.com/typescript/ts-tutorial.html
https://www.tslang.cn/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值