说说对Typescript中类的理解
# 是什么
和 js 中的 class 差不多,但比其丰富,多了修饰符和抽象类
- 支持类和接口
# 怎么用
- 字段
- 构造函数
- 方法
class Car {
// 字段
engine: string;
// 构造函数
constructor(engine: string) {
this.engine = engine;
}
// 方法
disp(): void {
console.log("发动机为 : " + this.engine);
}
}
# 继承
class A {
move: () => {};
}
class B extends A {
say: () => {};
}
const b = new B();
b.move();
# 修饰符
- readonly
- protected
- private
- public
- static
class A {
readonly name: string;
protected age: number;
private height: number;
static address: string;
}
# 抽象类
这种类并不能被实例化,通常需要我们创建子类去继承
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('roaming the earch...');
}
}
class Cat extends Animal {
makeSound() {
console.log('miao miao')
}
}
const cat = new Cat()
cat.makeSound() // miao miao
cat.move() // roaming the earch...
上次更新: 2021/12/19, 18:05:42