继承和多态
之前的JavaScript是基于原型(prototype)继承来实现可复用的“类”,而TypeScript是真正的实现了类,真正可以使用面向对象的编程思想。
class Animal {
name:string;
// Animal类的构造方法
constructor(theName: string) { this.name = theName; }
move(meters: number = 0) {
console.info(this.name + " moved " + meters + "m.");
}
}
// 继承
class Snake extends Animal {
constructor(name: string) { super(name); }
move(meters = 5) {
console.info("Slithering...");
super.move(meters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(meters = 45) {
console.info("Galloping...");
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
Horse类继承了Animal类 并且重写了move方法,这样move()方法在不同的类中就具有不同的功能,这就是多态。
派生类的构造函数必须调用super(),它会执行基类的构造方法。
修饰符
类中的修饰符有:public, private, protected三种类型。
class Animal {
public name:string; // 谁都可以访问
protected height:number; // 可在子类中访问
private weight:number; // 仅能在Animal中访问
// Animal类的构造方法
constructor(theName: string) { this.name = theName; }
move(meters: number = 0) {
console.info(this.name + " moved " + meters + "m.");
}
}
参数属性
如下例可以使用protected theName: string
限定构造函数的参数,
class Animal {
static type = {run:0, jump:1}; // 静态成员变量
name:string;
// Animal类的构造方法
constructor(protected theName: string) { this.name = theName; }
move(meters: number = 0) {
console.info(this.name + " moved " + meters + "m.");
}
}
抽象类
**简单来说,接口更注重功能的设计,抽象类更注重结构内容的体现。**
abstract class Animal {
abstrack eat():void; // 必须在派生类中实现
move(meters: number = 0) {
console.info(this.name + " moved " + meters + "m.");
}
}