Class와 getter, setter

class Person {
  private readonly _name: string;
  readonly age: number;

  constructor(name: string, age: number) {
    this._name = name;
    this.age = age;
  }

  get name(): string {
    return this._name + '222';
  }
}

const person = new Person('max', 30);
console.log(person.name);

참고 Object

Class와 static 프로퍼티 ⇒ 클래스 멤버 변수

static : 모든 인스턴스가 공유하는 자원

class Person {
  static HEIGHT: number = 172;
  private readonly _name: string;
  private readonly age: number;

  constructor(name: string, age: number) {
    this._name = name;
    this.age = age;
  }
}

console.log(Person.HEIGHT); // 172

Class와 private constructor

외부에서 인스턴스 생성이 불가능한 클래스이다. singleton 패턴에서 사용할 수 있다고 하는데 호불호의 여지가 있다고 한다.

class Person {
  private static instance: Person | null = null;
  name: string;

  private constructor(name: string) {
    this.name = name;
  }

  public static getInstance(): Person {
    if (this.instance === null) {
      this.instance = new Person('max');
    }

    return this.instance;
  }
}

const max = Person.getInstance();
console.log(max);

Class와 readonly