TypeScript的类,简单地定义如下:
class Person {
x: number; // 默认为public类型
y: number;
constructor(x1: number, y1: number) { // 默认为public类型
this.x = x1;
this.y = y1;
}
}
let test = new Person(12, 34)
ts中,定义一个类使用class关键字,使用new进行类的实例化,constructor关键字用来定义该类的构造函数。
参数属性
什么叫做参数属性,比如上面的x、y字段的声明和构造实例化是分两步进行的,可以归纳到如下一步:
class Person {
constructor(public x1: number, public y1: number) {} // 注意这里的实现
}
let test = new Person(12, 34)
继承
使用extends关键字可以实现类之间的继承,包括字段、方法的继承,看个例子:
class Person {
constructor(public x1: number, public y1: number) { }
greet() {
return this.x1 + '-' + this.y1;
}
}
class A extends Person {
constructor(x: number, y: number) {
super(x, y);
// ...
}
greet2() {
return this.greet()
}
}
let test = new A(12, 23);
console.log('extends from Person: ', test.greet()); // extends from Person: 12-23
console.log('self method: ', test.greet2()); // self method: 12-23
注意:
派生类包含了一个构造函数,它必须调用 super(),它会执行基类的构造函数。而且,在构造函数里访问 this的属性之前,我们一定要调用 super()。 这个是TypeScript强制执行的一条重要规则。
当然,调用super之后在A类中你可以像Person类中那样进行后续处理。
public修饰符
public修饰符可以表示字段或者方法是共有的,也就是说在子类和其它类是可访问的,如下:
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
let animal = new Animal('rabbit 兔子');
animal.move(1); // rabbit 兔子 moved 1m.
animal.name = '狗熊,忘了英文咋写了';
animal.move(200); // 狗熊,忘了英文咋写了 moved 200m.
private修饰符
private修饰符可以表示字段或者方法是私有的,也就是只在当前类中有效,出了该类是无法访问的,举个栗子:
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
class Rhino extends Animal {
constructor(public age: number) { super("Rhino"); }
}
let test = new Animal('狗娃');
// test.name // wrong!访问不到,因为name私有
let test2 = new Rhino(23);
test2.age // 23
protected修饰符
用protected修饰的字段只能在当前类及其子类中访问,被protected修饰的构造函数,构造函数所在的类不能直接直接进行new操作,但是该构造可以被子类继承,从而子类进行重新构造,但是还要首先调用super。
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' 的构造函数是被保护的.可以被继承,不能直接new
readonly修饰符
被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 是只读的.
get和set存取器
对于private字段,一般我们会在class中使用存取器进行赋值及调用,这就是get和set的作用。
class Person {
private _name: string;
set name(theName: string) {
console.log('-----------')
this._name = theName;
}
get name(): string {
return this._name + '********';
}
}
let test = new Person();
test.name = 'admin'
console.log(test.name)
输出如下:
-----------
admin********
注意:
get存取器必须要有返回值,没有返回值可以写void返回,返回不确定可以使用any类型。
静态属性
静态属性定义时,直接在属性或字段前面加上static修饰即可。
class Grid {
static origin = { x: 0, y: 0 };
static test;
constructor (public scale: number) { }
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;
}
testValue() {
console.log('testing: ', Grid.test);
}
}
let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10})); // 14.142135623730951
console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 })); // 2.8284271247461903
console.log(grid1.testValue()); // testing: undefined
注意:
static字段调用的时候直接使用:类名.字段名 调用,实例字段使用:(new Class).字段名 调用,当然class内部直接使用this调用。
抽象类
使用abstract关键字修饰一个抽象类,和接口不同的是,抽象类中可以有成员的实现细节,举个栗子:
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(); // 错误: 方法在声明的抽象类中不存在
let accountingDepartment: AccountingDepartment;
accountingDepartment = new AccountingDepartment();
accountingDepartment.generateReports();
注意:
1、abstract的class不能直接被new,只能被extends
2、abstract的method必须被子类实现