public 公共的

  1. class Animal {
  2. public name: string;
  3. public constructor(theName: string) {
  4. this.name = theName;
  5. }
  6. public move(distanceInMeters: number) {
  7. console.log(`${this.name} moved ${distanceInMeters}m.`);
  8. }
  9. }

private 私有的

  • 不能被外部访问,只能在类的内部访问使用
    - 私有成员不会被继承
class Person {
  public name: string;
  public age: number = 18;
  private type: string = 'human'
  public constructor (name:string, age:number) {
    this.name = name
    this.age = age
  }
}

protected 受保护的

  • 和 private 类似,但是可以被继承
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); // 错误

注意,我们不能在 Person类外使用 name,但是我们仍然可以通过 Employee类的实例方法访问,因为Employee是由 Person派生而来的。