class Animal {
public name: string;
public constructor(theName: string) {
this.name = theName;
}
public move(distabceInMeters: number) {
...
}
}
private
class Animal {
private name: string;
constructor(theName: string) {
this.name = theName;
}
}
new Animal('CAT').name; // error, 不能再声明它的类之外访问
protected
protected 与 privated 类似,但是 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); // 错误,不能在子类之外访问