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

`static` 멤버와 Class 의 `this`

~8 min · classes, static, this

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Static 멤버가 instance 가 아닌 class 에 살아. Static method 안 `this` 가 class 자체."

Static 멤버

static 가 각 instance 아닌 class 에 속하는 멤버 선언. class Foo { static count = 0 } 의미 `Foo.count` 가 모든 사용 가로질러 공유되는 한 값; `new Foo().count` 가 존재 안 함. Static 필드와 method 가 instance 아니라 class 이름 통해 접근.

흔한 사용: factory method (static create()), counter 나 registry (static instances: Foo[] = []), 상수 (static readonly MAX = 100).

Static method 안 `this`

Static method 안 `this` 가 (instance 아닌) class 자체 참조. static create(): Foo { return new this() } 가 `this` 통해 새 instance 만들어 — 그리고 여기 `this` 가 class. 이 패턴이 상속에 옳게 작동: subclass 의 `create` 가 호출하는 class 에 `this` 가 bind 되니까 parent 아닌 subclass constructor 호출.

`this` 타입

TypeScript 가 return annotation 으로 polymorphic `this` 타입 지원. class Builder { setX(): this } 가 "호출 site 의 `this` 가 뭐든 반환" 말함 — 보통 호출 class, 각 method 가 가장-derived 타입 반환하는 fluent 체이닝 가능. builder.setX().setY() 가 subclass 통해서도 작동.

`static` 이 class-레벨 state 용; `this` 타입이 instance-레벨 fluent API 용. 함께 전체 상속 계층 가로질러 작동하는 연산 원하는 대부분 case cover.

Code

Static 멤버와 polymorphic this·typescript
class Counter {
  static instances = 0;
  static readonly MAX = 100;

  // `new this()` 쓰는 factory method.
  static create(): Counter {
    Counter.instances++;
    return new this();
  }

  // Fluent 체이닝용 polymorphic `this`.
  reset(): this {
    return this;
  }

  count: number = 0;
}

class SafeCounter extends Counter {
  // Static instances 와 MAX 상속.
  // create() 가 `new this()` 통해 자동으로 Counter 아닌 SafeCounter 반환.
}

const c = Counter.create();              // c: Counter
const s = SafeCounter.create();          // s: SafeCounter — 같은 factory 패턴
Counter.instances;                       // 2

c.reset().reset();                       // ✅ fluent — 각각 `this` 반환

External links

Exercise

static level: 'info' | 'error' = 'info', prefix 받는 constructor, log(msg: string): void method 가진 Logger class 빌드. static setLevel(l: ...) 추가. Logger.level 이 모든 instance 가로질러 공유되는지 확인.
Hint
각 instance 가 현재 설정으로 Logger.level 읽어. Logger.setLevel('error') 한 번 호출이 모든 기존과 미래 logger 영향 — 그게 static 의 요점.

Progress

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

댓글 0

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

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