007--TypeScript之类的修饰符

类默认的修饰符是public

private

class Animal {
  private name: string 

  public constructor(name) {
    this.name = name 
  }

//  public move(distance: number){
//     console.log(`${this.name} is move ${distance} m`)
//   }
}

class Rhino extends Animal {
  constructor(){
    super('Rhino')
  }
}

class Employee {
  private name: string
  constructor(name: string){
    this.name = name
  }
}

let animal = new Animal('Goat')
let rhino = new Rhino()
let empolyerr = new Employee('Bob')

animal = rhino //这样做是可以的,因为rhino是animal的子类,rhino共享animal私有成员
//animal = empolyerr//报错,是因为两个类中的name都是私有成员

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
  }
  getElevatorPitch(){
    return `Hello, my name  is ${this.name} and i work in ${this.department}`
  }
}

let howard = new Employee('Howard','北京')
console.log(howard.getElevatorPitch())//Hello, my name  is Howard and i work in 北京
//console.log(howard.name)//报错,name属性受保护,只能在类'Person'及其子类中访问

现在我们给Person类的constructor加上protected

class Person {
  protected name:string 
  protected constructor(name: string) {
    this.name = name
  }
}

class Employee extends Person {
  private department: string 
  constructor(name: string, department: string){
    super(name)
    this.department = department
  }
  getElevatorPitch(){
    return `Hello, my name  is ${this.name} and i work in ${this.department}`
  }
}

let howard = new Employee('Howard','北京')
let person = new Person('john')//报错,Person类是受保护的,仅可在类声明中访问

readonly

可以被外部访问,不可以被外部修改

class Person {
  readonly name:string 
  constructor(name: string) {
    this.name = name
  }
}

let john = new Person('john')
john.name  //可以访问
//john.name = '' //报错,不能修改
//上述也可以写成这样(参数属性),但这样写代码逻辑不清晰,推荐上一种写法
class Person {
  constructor(readonly name: string) {
    this.name = name
  }
}

2019-05-24  17:39:00

工欲善其事,必先利其器
原文地址:https://www.cnblogs.com/ccbest/p/10919395.html