C.W.K.
Stream
Lesson 02 of 06 · published

`public`, `private`, `protected`, `#private`

~9 min · classes, access-modifiers, encapsulation

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"'이거 내 거' 말하는 4가지 방법. 3개가 TypeScript 전용; 하나가 JavaScript."

4개 modifier

  • `public` (default): 어디서나 접근 가능. Default 라서 명시 거의 안 써.
  • `protected`: 이 class 와 subclass 에서 접근 가능, 외부 안 됨.
  • `private` (TypeScript): TypeScript-only privacy — compile-시점 강제. Runtime 엔 property 가 `obj['name']` 통해 접근 가능한 일반 property.
  • `#private` (JavaScript): 진짜 private 문법. 숨겨진 slot 통한 runtime-강제. 외부 접근 시도가 parse 시점 SyntaxError 또는 runtime TypeError.

어느 거 써

새 TypeScript 코드엔: 진짜 private 필드, 특히 민감한 거 (auth token, internal handle, raw 메모리) 엔 `#private` 선호. 우회 못 함.

기존 코드엔: `private` 괜찮음 — compile-시점 contract 가 대부분 정당한 접근 실수 잡음. 더 강한 보장 원할 때 `#private` 로 migration 기계적.

상속 체인엔: subclass 가 필요한데 외부 caller 가 보면 안 되는 필드/method 엔 `protected`. Framework base class 의 흔한 패턴.

작동하는 default: 대부분 필드가 `private` (또는 `#private`) 여야. 대부분 method 가 `public` 이어야. `protected` 가 드문 중간 ground. 어디서나 public default 는 너무 leaky; 어디서나 private default 는 너무 제한적.

Code

4 modifier in action·typescript
class BankAccount {
  // TypeScript private — compile-시점만.
  private _balance: number = 0;

  // JavaScript private — runtime 강제.
  #internalToken: string = '';

  // Public method.
  deposit(amount: number): void {
    this._balance += amount;
  }

  // Read-only 접근용 public accessor.
  get balance(): number {
    return this._balance;
  }

  // Protected — subclass 가 쓸 수.
  protected validateAmount(amount: number): boolean {
    return amount > 0 && amount < 1_000_000;
  }
}

class SavingsAccount extends BankAccount {
  applyInterest(rate: number): void {
    if (this.validateAmount(rate)) {     // ✅ subclass 에서 protected 접근
      // this._balance 직접 접근 못 함 — parent-private
      this.deposit(this.balance * rate);
    }
  }
}

const acc = new BankAccount();
acc.balance;                     // ✅ public getter
// acc._balance;                 // ❌ private
// acc.#internalToken;           // ❌ SyntaxError — # 가 class 안에서만
// acc['_balance']               // ⚠️ runtime 에 TypeScript-private 접근

External links

Exercise

#password (진짜 private) 와 addPassword(p: string), match(p: string): boolean method 가진 PasswordVault class 써. Runtime 에 vault['#password'] 가 password 못 읽는지, subclass 도 못 접근하는지 (extend 시도하고 에러 알아채) 검증.
Hint
#private 필드가 class 안에서만 접근 가능 — 외부, subclass 다 안 됨. 그게 compile-only private 가 안 주는 runtime 보장.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.