类
继承
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);
}
}
class Horse extends Animal {
constructor(name: string) {
// 在使用this之前,一定要先调用父类的super()方法
super(name);
}
move(distanceInMeters = 45) {
console.log("Galloping...");
// 重写从父类继承的方法
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
// 声明tom为Animal类,但是new的是Horse类
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
// 调用的依然是Horse类的move方法
tom.move(34);
理解public , private , protected
public
- 在
TypeScript里,成员都默认为public。 你也可以明确的将一个成员标记成 public
理解private
- 当成员被标记成
private时,它就不能在声明它的类的外部访问
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; // 错误: 'name' 是私有的.
理解protected
protected 修饰符与 private 修饰符的行为很相似,但有一点不同, 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() {
// 不能在 Person 类外使用 name ,但是我们仍然可以通过 Employee 类的实例方法访问,
// 因为 Employee 是由 Person 派生而来的
return `hello,my name is ${this.name} and i work in ${this.department}`
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
// name被标记为protected在类的外部不可以访问
console.log(howard.name); // 错误
构造函数被标记为protected
构造函数也可以被标记成 protected 。 这意味着这个类不能在包含它的类外被实例化,但是能被继承
class Person {
protected name: string;
// 构造函数被标记为protected
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' 的构造函数是被保护的
// pageNumber at 125
浙公网安备 33010602011771号