class 类 修饰符

1. 修饰符 public 

  public: public修饰的属性 是公有的 在任何地方都能访问到 可以做修改赋值操作

  class Pet{

    public name:string;

    constcutor(name:string){

      this.name = name

    }

  }

 

  const petPig = new Pet('pig')

  console.log(petPig.name)

  petPig.name = "佩奇"

  console.log(petPig.name)

 

  输出结果

  

 

 

   

 

 

2. 修饰符  peivate 

  private :private 修饰的属性 不愿意对外访问 就使用 private 来进行修饰 只能在当前定义的类里面进行访问 在其它子类中进行访问会提示错误

  class Pet{

    private name:string;

    constcutor(name:string){

      this.name = name

    }

  }

 

 

 

 

3.  修饰符 protected  

  protected : 修饰的属性 private 有点类似 它的子类可以访问它的属性 不属于它的子类 访问会报错 类似于 它的遗产只能它的子女来继承

  class Pet{

    protected name:string;

    constcutor(name:string){

      this.name = name

    }

  }

 

 

 

 

 

 

4.  修饰符 readonly 

   readonly:readonly 修饰的属性 只能读 不能改

  class Pet{

    readonly name:string;

    constcutor(name:string){ 

      this.name = name

    }

  }

 

 

 

5. static

  static:可以定义静态属性 也可以定义 静态方法   可以直接访问的属性 不需要实例化 可以直接在类上进行调用 static 可以用于定义 跟当前实例没有关系的属性 用于直接访问 

  

  5.1 定义静态属性

  class Pet{
      name:string;
      static categories:string[] = ["飞行类","爬行类"];   
      constructor(name:string){
          this.name = name
      }
      run(){
          return `${this.name} is runing`
      }
  }
  console.log(Pet.categories)
 

输出结果

 

 

 

 

  5.2 定义静态方法

  class Pet{
      name:string;
      static categories:string[] = ["飞行类","爬行类"]
      static isPet(a:any){
          return a instanceof Pet
      }
      constructor(name:string){
          this.name = name
      }
      run(){
          return `${this.name} is runing`
      }
  }

  const petPig = new Pet('pig')
  静态方法调用
  console.log(Pet.isPet(petPig))
 
输出结果

 

 

 

 

 

posted @ 2021-11-02 17:43  虹猫淘气  阅读(562)  评论(0编辑  收藏  举报