-
类包含的概念
-
类中定义的所有信息叫成员
-
成员有三种(属性,构造函数,方法)
-
属性 greeting
-
构造函数 constructor
-
方法 greet
class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } }
-
-
-
类的继承
-
通过继承扩展现有类
-
被继承的类叫
基类,继承的类叫派生类, 通过 extends 关键字实现 -
派生类通常被称作
子类,基类通常被称作超类 -
下图中 Animal 是基类,也是超类。Dog 是派生类,也是子类。
-
派生类有时候会包含构造函数,它 必须调用 super(),它会执行基类的构造函数。 而且,在构造函数里访问 this 的属性之前,我们 一定要调用 super()
class Animal { name: string; constructor(theName: string) { this.name = theName; } move(distanceInMeters: number = 0) { console.log(
Animal moved ${distanceInMeters}m.); } }class Dog extends Animal { constructor(name: string) { super(name); } bark() { console.log("Woof! Woof!"); } }
const dog = new Dog(); dog.bark(); dog.move(10); dog.bark();
-
-
类的属性
-
public 公共属性是默认的 ,也可以写,也可以不写
-
private 当成员被标记成 private 时,它就不能在声明它的类的外部访问。new 这个的实例无法访问这个属性
-
protected 成员在派生类中仍然可以访问,比如通过 this 访问,构造函数也可以被标记为 protected
-
属性可以被标记为 readonly,只能读不能改
-
static 静态属性,这些属性存在于类本身上面而不是类的实例上
class Person { protected name: string; constructor(name: string) { this.name = name; } }
class Employee extends Person { private department: string;
constructor(name: string, department: string) { super(name) this.department = department; }
public getElevatorPitch() { return
Hello, my name is ${this.name} and I work in ${this.department}.; } }let howard = new Employee("Howard", "Sales"); console.log(howard.getElevatorPitch()); console.log(howard.name); // 错误
我们不能在 Person 类外使用 name,但是我们仍然可以通过 Employee 类的实例方法访问,因为 Employee 是由 Person 派生而来的
-
-
存取器 get 方法和 set 方法
let passcode = "secret passcode"; class Employee { private _fullName: string; 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); } -
抽象类 abstract
- 抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。 不同于接口,抽象类可以包含成员的实现细节。 abstract 关键字是用于定义抽象类和在抽象类内部定义抽象方法
-
类可以当做接口使用
class Point { x: number; y: number; } interface Point3d extends Point { z: number; } let point3d: Point3d = { x: 1, y: 2, z: 3 }; -
子类中使用 super 关键字来调用父类的构造函数和方法
class Animal { public name; constructor(name) { this.name = name; } sayHi() { return `My name is ${this.name}`; } } let a = new Animal('Jack'); console.log(a.sayHi()); // My name is Jack class Cat extends Animal { constructor(name) { super(name); // 调用父类的 constructor(name) console.log(this.name); } sayHi() { return 'Meow, ' + super.sayHi(); // 调用父类的 sayHi() } } let c = new Cat('Tom'); // Tom console.log(c.sayHi()); // Meow, My name is Tom