说在前面
这里主要将ts中类的使用的一些特性,和其他语言面向对象相通的地方这里就不做多余赘述。
readonly修饰符和参数属性
使用 readonly
关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。
将只读属性作为构造函数的参数传入。参数属性可以方便地让我们在一个地方定义并初始化一个成员
class Octopus {
readonly numberOfLegs: number = 8;
constructor(readonly name: string) {
}
}
super()
派生类包含的构造函数必须super();
如果构造函数中需要访问this,需要在之前调用super();
执行父类的普通方法,使用super.functionName();
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
存取器
存取器可以拦截对类中属性的访问和设置。在set和get方法中对数据进行处理或者过滤。
class Employee {
_fullName: string;
set fullName(name: string) {
console.log("您将要设置_fullName的值:");
this._fullName = name;
}
get fullName(): string {
console.log("您将要获取_fullName的值:");
return this._fullName;
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
静态属性和静态方法
定义:方法或者属性前面添加 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(Grid.origin.x);
console.log(Grid.origin.y);
console.log(grid1.calculateDistanceFromOrigin({ x: 10, y: 10 }));
console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 }));