TypeScript 具备面向对象编辑的基础语法,包括interface,class ,enum等;也具备封装,基础,多态等面向对象的基本特征
//定义矩形类
class Rectangle {
//成员变量
private width: number
private length:number
//构造函数
constructor(width:number,length:number){
this.width = width;
this.length = length;
}
//成员方法
public area(): number{
return this.width * this.length
}
}
//定义正方形
class Square extends Rectangle{
constructor(side:number){
//调用父类构造
super(side,side)
}
}
let s = new Square(10)
console.log('正方形面积为:'+s.area())
//类、接口、枚举
//定义枚举
enum Msg{
HI = 'Hi',
HELLO = 'Hello'
}
//定义接口,抽象方法接收枚举参数
interface A{
say(msg: Msg):void
}
//实现接口
class B implements A{
say(msg: Msg):void {
console.log(msg +'I am B')
}
}
//初始化对象
let a:A = new B()
// 调用方法,传递枚举参数
a.say(Msg.HI)