Typescript: 상속 및 정적 멀버

에 λ§Œλ“  2015λ…„ 12μ›” 08일  Β·  1논평  Β·  좜처: microsoft/TypeScript

정적 멀버에 μ•‘μ„ΈμŠ€ν•˜λŠ” 데 μœ μš©ν•˜λ‹€κ³  μƒκ°ν•©λ‹ˆλ‹€.

  • μΈμŠ€ν„΄μŠ€μ—μ„œ
  • ν•˜μœ„ ν΄λž˜μŠ€μ—μ„œ

예 μ•„λž˜:

class A {
  protected static type: string;

 public log(): string {
    console.log(this.type);
  }
}

class B extends A {
  protected static type: string = 'C';
}

class C extends A {
  protected static type: string = 'C';
}

b = new B();
b.log(); // => 'B'

c = new C();
c.log(); // => 'C'
By Design Declined Suggestion

κ°€μž₯ μœ μš©ν•œ λŒ“κΈ€

this.type λŠ” _static_ 속성이 μ•„λ‹ˆλΌ type λΌλŠ” _instance_ 속성에 μ•‘μ„ΈμŠ€ν•˜λŠ” 데 μ‚¬μš©λ˜λ―€λ‘œ μ œμ•ˆν•˜μ‹  λ°©μ‹μœΌλ‘œ ν•  수 μ—†μŠ΅λ‹ˆλ‹€.

κ·ΈλŸ¬λ‚˜ λ‹€μŒκ³Ό 같이 μž‘μ„±ν•˜λ©΄ μ˜ˆμ œκ°€ μž‘λ™ν•©λ‹ˆλ‹€.

class A {
  "constructor": typeof A;  // Explicitly declare constructor property
  protected static type: string;

  public log() {
    console.log(this.constructor.type);  // Access actual constructor object
  }
}

class B extends A {
  protected static type: string = 'B';
}

class C extends A {
  protected static type: string = 'C';
}

let b = new B();
b.log(); // => 'B'

let c = new C();
c.log(); // => 'C'

기본적으둜 μΈμŠ€ν„΄μŠ€μ˜ constructor 속성은 Function μœ ν˜•μ΄μ§€λ§Œ μˆ˜λ™μœΌλ‘œ μ„ μ–Έν•˜μ—¬ ν΄λž˜μŠ€μ—μ„œ νŠΉμˆ˜ν™”ν•  수 μžˆμŠ΅λ‹ˆλ‹€. κ·Έλ ‡κ²Œ ν•˜λ©΄ this.constructor.xxx 톡해 statics에 μ•‘μ„ΈμŠ€ν•  수 있으며 μ‹€μ œλ‘œ μΈμŠ€ν„΄μŠ€λ₯Ό μƒμ„±ν•œ μƒμ„±μž 객체(즉, νŒŒμƒλœ μƒμ„±μž 객체)의 속성을 얻을 수 μžˆμŠ΅λ‹ˆλ‹€.

>λͺ¨λ“  λŒ“κΈ€

this.type λŠ” _static_ 속성이 μ•„λ‹ˆλΌ type λΌλŠ” _instance_ 속성에 μ•‘μ„ΈμŠ€ν•˜λŠ” 데 μ‚¬μš©λ˜λ―€λ‘œ μ œμ•ˆν•˜μ‹  λ°©μ‹μœΌλ‘œ ν•  수 μ—†μŠ΅λ‹ˆλ‹€.

κ·ΈλŸ¬λ‚˜ λ‹€μŒκ³Ό 같이 μž‘μ„±ν•˜λ©΄ μ˜ˆμ œκ°€ μž‘λ™ν•©λ‹ˆλ‹€.

class A {
  "constructor": typeof A;  // Explicitly declare constructor property
  protected static type: string;

  public log() {
    console.log(this.constructor.type);  // Access actual constructor object
  }
}

class B extends A {
  protected static type: string = 'B';
}

class C extends A {
  protected static type: string = 'C';
}

let b = new B();
b.log(); // => 'B'

let c = new C();
c.log(); // => 'C'

기본적으둜 μΈμŠ€ν„΄μŠ€μ˜ constructor 속성은 Function μœ ν˜•μ΄μ§€λ§Œ μˆ˜λ™μœΌλ‘œ μ„ μ–Έν•˜μ—¬ ν΄λž˜μŠ€μ—μ„œ νŠΉμˆ˜ν™”ν•  수 μžˆμŠ΅λ‹ˆλ‹€. κ·Έλ ‡κ²Œ ν•˜λ©΄ this.constructor.xxx 톡해 statics에 μ•‘μ„ΈμŠ€ν•  수 있으며 μ‹€μ œλ‘œ μΈμŠ€ν„΄μŠ€λ₯Ό μƒμ„±ν•œ μƒμ„±μž 객체(즉, νŒŒμƒλœ μƒμ„±μž 객체)의 속성을 얻을 수 μžˆμŠ΅λ‹ˆλ‹€.

이 νŽ˜μ΄μ§€κ°€ 도움이 λ˜μ—ˆλ‚˜μš”?
0 / 5 - 0 λ“±κΈ‰