1. 类的继承和基本类型指定
ts中super必须被调用,否则会提示
Constructors for derived classes must contain a 'super' call
super在子类中有三种形式:
1. 在子类的构造函数中表示父类的构造函数。
2. 在子类的普通函数中相当于父类的原型对象。
3. 在子类的静态函数中相当于父类本身。
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); } // 1.相当于super.call(this, props)
move(distanceInMeters = 45) {
console.log("Galloping...");
// 2. 相当于super.prototype.move.call(this, distanceInMeters) super.move(distanceInMeters);
}
}
let tom: Animal = new Horse("Tommy the Palomino");
tom.move(34);
2. 修饰符(公共/私有/受保护)
1. 公共-public
在ts中,类的所有的成员默认为public。可以被任意访问
上面的类本质上为:
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
2. 私有-private
只能在声明它的类内部访问
class Animal { private name: string; constructor(theName: string) { this.name = theName; }}new Animal("Cat").name; // 错误: 'name' 是私有的.
private的成员可以被继承
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
class Rhino extends Animal {
constructor() { super("Rhino"); }
}
class Employee {
private name: string;
constructor(theName: string) { this.name = theName; }
}
let animal = new Animal("Goat");
let rhino = new Rhino();
let employee = new Employee("Bob");
animal = rhino; // 正确。两者共享private成员
animal = employee; // 错误: Animal 与 Employee 不兼容.
3. 受保护-protected
只能在声明它的类内部和子类(派生类)内部访问。
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); // 错误;只能在声明类和子类中访问
构造函数被标记为protected时,该构造函数不能被实例,但是可以被继承
class Person {
protected name: string;
protected constructor(theName: string) { this.name = theName; }
}
// Employee 能够继承 Person
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");
let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.
3. readonly修饰符
1. 只读 2. 必须在声明或者构造函数中被初始化
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 是只读的.
构造函数的参数属性
构造函数的参数可以定义并初始化一个成员
class Octopus { // 和上面的代码等价
readonly numberOfLegs: number = 8;
constructor (readonly name: string) {
}
}
4. 存取器(get/set)
只有get而没有set的存取器自动被推断为readonly
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);
}
5. 静态属性static
直接通过类访问
class Grid {
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
let xDist = (point.x - Grid.origin.x);
let yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor (public scale: number) { }
}
let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));
6. 抽象类-abstract
abstract作用:
- 定义抽象类(抽象类不能被实例化)
- 定义抽象类内部的抽象方法(不包含具体实现并且必须在派生类中实现)
abstract应用:
abstract class Animal { // 抽象类
abstract makeSound(): void; // 抽象方法不包含具体实现
move(): void { // 非抽象方法可以包含具体实现
console.log('roaming the earch...');
}}
示例:
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");
}
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.printMeeting();
department.printName();
department.generateReports(); // ❌方法声明在抽象类中不存在
6. 高级技巧-构造函数
在ts中声明类的时候,同时声明了实例类型和构造函数。
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter: Greeter;
greeter = new Greeter("world");
console.log(greeter.greet());
其编译成javascript的结果如下:
var Greeter = (function() {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function() {
return "Hello, " + this.greeting;
}
return Greeter
}());
var greeter;
greeter = new Greeter("world");
console.log(greeter.greet());