class类的TS语法
类中成员的
public、private、protected、readonly
修饰符的理解, 像static、get、set
再js中也有就不说了
- public 默认修饰符,可以自由访问
- private 当成员被标记成 private时,它就不能在声明它的类的外部访问 跟#修饰符一样。
- protected protected修饰符与 private修饰符的行为很相似,但有一点不同, protected成员在派生类中仍然可以访问。
- readonly 使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。
ts
class Animal {
public x: number;
public y: number;
private isMove: boolean;
constructor() {
}
private makeSound(): void {
}
private move(): void {
console.log('roaming the earch...');
}
}
抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。 不同于接口,抽象类可以包含成员的实现细节。 abstract关键字是用于定义抽象类和在抽象类内部定义抽象方法。
ts
abstract class Animal {
abstract makeSound(): void; // abstract 必须再声明类中声明
move(): void {
console.log('roaming the earch...');
}
}
ts
abstract class Department {
constructor(public name: string) {
}
printName(): void {
console.log('Department name: ' + this.name);
}
abstract printMeeting(): void; // 必须在派生类中实现
}
class AccountingDepartment extends Department {
constructor() {
super('Accounting and Auditing'); // 在派生类的构造函数中必须调用 super()
}
printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports(): void {
console.log('Generating accounting reports...');
}
}
let department: Department; // 允许创建一个对抽象类型的引用
department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
department.generateReports(); // 错误: 方法在声明的抽象类中不存在
implements
implements
再类上也经常看到,其实就是定义一个类的方法入参,返回值之类的。
ts
interface Basic {
getUserName(): string,
setUserName(name: string): void,
}
class User implements Basic {
getUserName() {
return '小明'
}
setUserName(name: string) {
console.log(name,'name')
}
}