class是一种比较常见的自定义类型,注意class Person除了在类型声明空间提供了一个Person的类型,也在变量声明空间提供了一个可以使用的变量Person用于实例化对象。 下面是一个简单的例子:
class Person{
private age:number;//只能被当前类访问
protected name:string;//只能被当前类及其子类访问
public gender:number;//可在实例化对象上访问
constructor(name:string,age:number,gender:number){
this.age = age;
this.name = name;
this.gender = gender;
}
public show(){
console.log(`姓名:${this.name},年龄:${this.age},年级:${this.gender}`)
}
}
let p:Person = new Person("puff",30,3);
console.log(p.gender)//3
//console.log(p.name)//会报错
//console.log(p.age)//会报错
p.show()
//继承
class Student extends Person{
static count:number = 0;//静态属性
readonly height:string = undefined;//初始化只读属性
constructor(name:string,age:number,gender:number,height:string){
super(name,age,gender);
this.height = height;//只读属性只能在声明时或者构造函数中初始化
Student.count++ //在子类中调用静态属性只能这样写
}
show(){//重写父类的方法
// this.height="180"//会报错
console.log("this.height",this.height)
super.show()
Student.getCount()//静态方法只能被子类调用
}
static getCount(){
console.log("getCount~",Student.count)//1
// this.show()//会报错 静态方法中不能调用实例方法
}
}
let s:Student = new Student("lics",27,3,'160')
s.show()
参考链接
学习Typescript