ES6中也增加了class关键字,TypeScript类的定义和继承
// 类定义
class Person {
name = 'Brady';
getName() {
return this.name;
}
}
// 子类继承
class Teacher extends Person {
// 子类方法
getTeacherName() {
return 'Teacher';
}
// 子类重写父类方法
getName() {
// 使用 super 调用父类原有方法
return super.getName() + '' + this.getTeacherName();
}
}
// 创建对象
const person = new Person();
const teacher = new Teacher();
console.log(person.getName());
console.log(teacher.getName());
console.log(teacher.getTeacherName());
访问类型: public、protected、private、
- public:允许在类的内外调用
- protected:允许在类的内部及继承的子类中调用
- private:允许在类的内部调用
构造函数 constructor
class Person {
// 传统
// public name: string;
// constructor(name: string) {
// this.name = name;
// }
// 简化
constructor(public name: string) {}
printName(): void {
console.log(this.name);
}
}
class Teacher extends Person {
constructor(public name: string, public age: number) {
super(name);
}
printAge(): void {
console.log(this.name, this.age);
}
}
const person = new Person('Brady');
person.printName();
const teacher = new Teacher('Jack', 18);
teacher.printAge();
getter 和 setter 对私有属性的保护
class Person {
constructor(private _name: string) {}
get name() {
return `${this._name} Li`;
}
set name(name: string) {
const realName = name.split(' ')[0];
this._name = realName;
}
}
const person = new Person('Brady');
console.log(person.name);
person.name = 'Jack Li';
console.log(person.name);
单例模式示例
/**
* 单例模式
*/
class Demo {
private static instance: Demo;
private constructor(public name: string) {}
static getInstance() {
!this.instance ? (this.instance = new Demo('Brady Li')) : '';
return this.instance;
}
}
const demo1 = Demo.getInstance();
const demo2 = Demo.getInstance();
console.log(demo1.name);
console.log(demo2.name);
readonly 只读属性
class Person {
constructor(public readonly name: string) {}
}
const person = new Person('Brady');
console.log(person.name);
抽象类
/**
* 抽象类
*/
abstract class Geom {
constructor(public width: number) {}
getType() {
return 'Geom';
}
// 抽象方法
abstract getArea(): number;
}
// 圆形类
class Circle extends Geom {
getArea() {
return 123;
}
}
// 方形类
class Square {}
// 三角形类
class Triangle {}