0

Typescript中的模块和继承

 1 year ago
source link: https://blog.51cto.com/u_13349380/5635360
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Typescript中的模块和继承

精选 原创
Typescript中的模块和继承_构造函数

ts也只是ES Module规范定义模块。并且允许我们在代码中,通过module关键字定义内部的模块

此时模块内部的信息是隐秘的,想使用,必须在模块内部通过export关键字将其暴露出来

ts中的模块是通过闭包实现的。

// 定义模块
module Ickt {
// 使用什么数据,就要通过export关键字,将其暴露出来
export let color = 'red';
// ts是es6语法的超集,因此es6语法,ts也支持的,例如箭头函数等
export function add(num1:number, num2:number):number {
return num1 + num2;
}
}
console.log(Ickt.color)
console.log(Ickt.add(10, 20))

es6中有继承,通过extends关键字定义,

ts也支持,我们也可以通过extends关键字实现继承

当我们的子类继承父类后,我们可以属性,方法,甚至是构造函数,但是重写构造函数的时候,一定要通过super关键字实现构造函数式继承

super方法传递的参数,将在父类构造函数执行的时候使用。

super一定要在最前面执行

ES6中的ES Module规范就是出自于ts,所以我们也可以在ts中使用ES Module规范

在webpack中,省略引入文件的拓展名,配置extensions。

ts中的继承是一个寄生组合式的继承。

// 引入book类
import { Book } from './04';
// 定义tsbook子类
class TsBook extends Book {
// 静态属性
static year:number = 2021;
// 重写属性
color: string;
// 重写构造函数
constructor(title:string, page:number, color) {
// 构造函数继承
super(title, page);
// 子类中,存储数据,要在构造函数式继承之后存储
this.color = color;
}
// 重写方法
getColor():string {
return this.color.toUpperCase()
}
}
// 实例化子类
var zss = new TsBook('设计模式', 25, 'green')
console.log(zss)
console.log(TsBook.year)
console.log(TsBook.writer)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK