sai_dive IL

学んだことのアウトプットブログ

【TypeScript】private修飾子

private修飾子

  • クラス内にprivate修飾子を使うことでクラス外で参照できなくする
class Person {
   private name: string;
   private age: number;
   constructor(initName: string, initAge: number) {
        this.name = initName;
        this.age    = initAge; 
   }
  private incrementAge() {
      this.age += 1;
  }
}

クラス外で以下のようにnameとageが呼び出せない
const sai = new Person('sai', 20);
console.log(sai.name);
console.log(sai.age);
クラス外で以下のようにincrementAge()も呼び出せない
sai.incrementAge();