Typescript的类
类的定义
class Person {name:string; // 定义属性,不写修饰符默认为public// 构造方法constructor(name:string) {this.name = name;}// 定义类中的方法getName():string{return this.name;}setName(name:string):void {this.name = name;}}// 类对象的实例化var p = new Person('张三');p.getName();
类中的readonly只能在声明或构造函数中被初始化
class Octopus {readonly name: string;readonly numberOfLegs: number = 8;constructor (theName: string) {this.name = theName;}}let dad = new Octopus("Man with the 8 strong legs");dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
类的继承
// 使用extends关键字继承class Student extends Person {constructor(name:string) {super(name); // 使用super调用父类的构造方法}work():string {return `${this.name} 在工作`;}// 重写父类方法getName():string{return this.name + '...';}}
修饰符
属性修饰符(不加修饰符时,默认为public)
- public : 共有,在类的里面、子类、类外面都可以访问
- protected : 保护,在类的里面、子类可以访问,在类外部不能访问
- private : 私有,在类里面可以访问。在子类和类外部都不能访问
静态属性/静态方法
class Person {public name:string;static sex:string = '男'; // 静态属性constructor(name:string) {this.name=name;}// 静态方法static print():void {alert(`${this.sex}`); // 静态方法中只能调用静态属性}}// 静态属性和静态方法不需要实例化对象,可直接通过类名调用Person.print();alert(Person.sex);
多态
父类定义一个方法不去实现,让继承它的子类去实现,每一个子类有不同的表现。
多态属于继承。
class Animal {name:string;constructor (name:string) {this.name = name;}eat() {console.log('吃function');}}class Dog extends Animal {constructor(name:string) {super(name);}eat() {alert('狗吃肉');}}class Cat extends Animal {constructor(name:string) {super(name);}eat() {alert('猫吃老鼠');}}
抽象类
typescript 中的抽象类: 是提供其他类继承的基类,不能直接被实例化
用abstract 关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现
abstract抽象方法只能放在抽象类中
// 抽象类使用ababstract class Animal {name:string;constructor (name:string) {this.name = name;}abstract eat():void;}
存取器
类似Java的setter/getter方法。
只有get没有set的存取器会自动被推断为readonly
let passcode = "secret passcode";class Employee {private _fullName: string;// 等同于创建了一个fullName变量,get获取其值,set为其赋值get fullName(): string {return this._fullName;}set fullName(newName: string) {if (passcode && passcode == "secret passcode") {this._fullName = newName;}else {console.log("Error: Unauthorized update of employee!");}}}let employee = new Employee();employee.fullName = "Bob Smith";if (employee.fullName) {alert(employee.fullName);}
