zoukankan      html  css  js  c++  java
  • 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

    工欲善其事,必先利其器
  • 相关阅读:
    「SHOI2015」脑洞治疗仪
    LOJ 数列分块入门 8
    CF932F Escape Through Leaf
    NOIP2021游记总结
    [HEOI2016/TJOI2016]序列
    【模板】动态树(Link Cut Tree)
    LG P2839 [国家集训队]middle
    JZOJ 7377.欢乐豆
    JZOJ 7392. 【2021.11.17NOIP提高组联考】数 (ds)
    LOJ 数列分块入门 6
  • 原文地址:https://www.cnblogs.com/ccbest/p/10919395.html
Copyright © 2011-2022 走看看