TS class类的定义、extends类的继承、属性修饰符、implements类的接口实现、abstract抽象类
1. class类定义
class Person {
name:string
age:number
address:string
constructor(name:string,age:number,address:string) {
this.name = name
this.age = age
this.address = address
}
}
let p1 = new Person("ccc", 22, "china")
console.log(p1)
2. extends类继承
class Person {
name:string
age:number
address:string
constructor(name:string,age:number,address:string) {
this.name = name
this.age = age
this.address = address
}
}
// 使用 extends 继承 Person 类
class Man extends Person {
sex:number
constructor(name:string,age:number,address:string, sex:number) {
super(name, age, address)
this.sex = sex
}
}
let p1 = new Man("ccc", 22, "china", 1)
console.log(p1) // Man { name: 'ccc', age: 22, address: 'china', sex: 1 }
3. 属性修饰符(static、public、protected、private)
class Person {
static s = "static"
name1:string
protected age:number
private address:string
constructor(name1:string,age:number,address:string) {
this.name1 = name1
this.age = age
this.address = address
}
static fun() {
// static 修饰的方法无法访问其他修饰符修饰的变量
this.name1 // 报错
this.s // 可以访问
}
}
class Man extends Person {
sex:number
constructor(name:string,age:number,address:string, sex:number) {
super(name, age, address)
this.sex = sex
this.address // 报错:address 为 private 私有变量
}
}
let p1 = new Man("ccc", 22, "china", 1)
p1.s // 报错:static 修饰的变量无法在实例上访问
Person.s // 可以访问
p1.name1 // 可以访问
p1.age // 报错:protected 修饰的变量无法在实例上访问
4. implements类的接口实现
interface F {
// 接口中只能包含抽象方法,不能有具体实现
cName: () => void
}
class Person implements F {
name: string
age: number
address: string
constructor(name: string, age: number, address: string) {
this.name = name
this.age = age
this.address = address
}
// 需要对 interface F 中有具体的方法实现
cName():void {
console.log(this.name);
}
}
let p1 = new Person("ccc", 22, "china")
p1.cName() // ccc
5. abstract抽象类
abstract class Person {
name1:string
constructor(name1:string) {
this.name1 = name1
}
abstract cName():void
}
let p1 = new Person("chenxize")
class Man extends Person {
age:number
constructor(name:string, age:number) {
super(name)
this.age = age
}
cName():void {
console.log(this.name1);
}
}
let m1 = new Man("chenxize", 22)
console.log(m1);