1. 类的定义
class City {
// 成员变量,定义在类中,如果没有在构造函数中初始化则需要在此处赋初始值
cname: string;
clevel: number;
// 构造函数:初始化
constructor(cName: string, cLevel: number) {
this.cname = cName;
this.clevel = cLevel;
}
// 成员方法:直接定义在类中,会被写入原型中
about() {
console.log('about');
}
}
let c1 = new City('P城', 1);
2. 类的继承
// 同 ES6
class CityChild extends City {
constructor(cName: string, cLevel: number) {
super(cName, cLevel)
}
}
3. 类修饰符
public
:公有,在类里面、子类、类外部都可以访问protected
:保护类型,在类里面、子类可以访问,在类外部无法访问private
:私有类型,在类里面可以访问,子类和类外部无法访问。 ```typescript // 父类,即类内部 class Father { // 类内部、子类、类外部可使用 public say() { console.log(‘say’) } // 类内部、子类可使用,类外部不可使用 protected money() { console.log(‘money’) } // 仅类内部使用 private wife() { console.log(‘my wife’) } useMethod() { this.say(); this.money(); this.wife(); } } // 子类 class Son extends Father { useMethod() { this.say(); this.money(); } } // 类外部 const father = new Father(); father.say();
<a name="vcf4B"></a>
# 4. 静态属性和静态方法
类中设置了 `static` 关键字的属性或方法,只能通过类去调用,不能通过类的实例调用。
> ES6 的语法
```javascript
class Father {
static run() {
console.log('run')
}
}
// 正确
Father.run();
// 错误
const father = new Father();
father.run();
5. 访问器
getter
和 setter
可以用来实现数据的封装和有效性检查,防止出现异常数据
ES6 的语法
let passcode = "Hello TypeScript";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "Hello TypeScript") {
this._fullName = newName;
} else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Semlinker";
if (employee.fullName) {
console.log(employee.fullName);
}
6. 抽象类
abstract
关键字定义抽象类、抽象方法和属性,抽象类中的抽象方法和属性不包含具体实现。
继承自抽象类的类,叫做派生类。 派生类必须实现抽象类的方法和属性
abstract class Animal {
abstract name: string;
abstract eat(): void;
}
class Dog extends Animal {
name = "dog";
// 必须实现抽象类的抽象方法
eat() { }
}