1. 程式人生 > 其它 >class 類 修飾符

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{

    privatename: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)) 輸出結果