定义 class
class PERSON {
name:string
constructor(name:string){
this.name = name;
}
getName(){return this.name;}
}
let wj = new PERSON('WJ')
继承 extends
不同的叫法:
PERSON:父类、基类、超类
STUENT:子类、派生类
// 父类
class PERSON {
name:string
constructor(name:string){
this.name = name;
}
getName(){return this.name;}
}
// 子类
class STUDENT extends PERSON{
student_id:number
scores:number
constructor(name:string, id:number){
super(name)
this.student_id = id;
}
setScores(scores:number){
this.scores = scores
}
}
// 实例
let wj = new STUDENT('WJ',203194)
wj.getName()
wj.setScores(98)
属性/方法修饰符 public、private、protected、readonly、static
public 共有
:可以在被实例
private 私有
:只能在定义的类内部使用,不能继承、不能实例化
protected 保护
:可以在定义的类内部和子类内部使用,不能实例化;需要外部获取时,可以通过public方法返回
readonly 只读
:可以被实例化;不能被修改,只能在创建或者构造函数里被初始化
static 静态
:只能通过类名获取PERSON.is_person,不能通过this.is_person获取
class PERSON {
public name:string
protected age:number = 18
private is_valid:boolean
readonly role:string = 'human'
static is_person:boolean = true
constructor(name:string){
this.name = name;
console.log(PERSON.is_person); // 获取静态属性
}
}
class STUDENT extends PERSON{
constructor(name:string,age?:number){
super(name)
}
getAge(){
return this.age;
}
}
let student = new STUDENT('WJ'); // 输出:STUDENT {age: 18, name: "WJ"}; age可以看到,但获取会报错
let person = new PERSON('WanJin'); // 输出:PERSON {age: 18, name: "WanJin"}; age可以看到,但是获取会报错
student.age; // 报错
student.getAge(); // 输出:18
PERSON.is_person; // 输出:true
contructor的参数中直接定义属性
下面两种写法的结果是相同的
class PERSON {
public name:string
private age:number
protected sex:number
readonly role:string
constructor(name:string, my_age:number, sex:number, role:string){
this.name = name;
this.age = my_age;
this.sex = sex;
this.role = role;
}
}
class PERSON {
constructor(public name:string, private age:number, protected sex:number, readonly role:string){
}
}
存取器getter、setter
class PERSON {
private _name: string
get name(): string {
return this._name
}
set name(new_name: string) {
let is_allow = true; // 用来检查该用户是否有此权限
if (is_allow)
this._name = new_name
}
}
let person = new PERSON();
person.name = 'WJ'; // 被set拦截,用来修改_name值
person.name; // 被get拦截,用来返回_name值;输出: 'WJ'
抽象类 abstract
不能实例化,只能被继承
类似接口,定义一个规范但没函数体也不实现具体动作,让子类实现父类中定义的方法
// 抽象类父类PERSON中,定义抽象方法setName的规范
abstract class PERSON {
abstract setName(name:string): void
}
// 子类根据父类的抽象类方法,实现具体的setName函数体
class STUDENT extends PERSON {
constructor(public name: string) {
super()
}
setName(name: string): void {
this.name = name;
}
}
let student = new STUDENT('WJ')
其他
class申明类的同时,也申明了实例的类型
(等同于接口interface)
// class声明PERSON类的同时,也声明了PERSON实例的类型
class PERSON {
constructor(public name: string) {
}
getName(){return this.name;}
}
// 实例person的类型为PERSON
let person: PERSON;
person = new PERSON("WJ");
console.log(person.getName());
网友评论