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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值