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

    工欲善其事,必先利其器
  • 相关阅读:
    免费的视频、音频转文本
    Errors are values
    Codebase Refactoring (with help from Go)
    Golang中的坑二
    Cleaner, more elegant, and wrong(msdn blog)
    Cleaner, more elegant, and wrong(翻译)
    Cleaner, more elegant, and harder to recognize(翻译)
    vue控制父子组件渲染顺序
    computed 和 watch 组合使用,监听数据全局数据状态
    webstorm破解方法
  • 原文地址:https://www.cnblogs.com/ccbest/p/10919395.html
Copyright © 2011-2022 走看看