Decorators - The-Next-Web-Research-Lab/the-next-web-research-lab.github.io GitHub Wiki


title: JavaScript - Decorators

JavaScript - Decorators Proposal๊ณผ ์‹ค์šฉ์„ฑ

Decorators Proposal

  • tc39/proposal-decorators์— ์ œ์•ˆ์„œ ์ •์˜๋จ
  • Orthogonal Classes์™€ Class Evaluation Order ์ œ์•ˆ์„ ๋ฐ”ํƒ•์œผ๋กœ Decorators์™€ Class Field ๋ฐ Private methods๋ฅผ ํ•จ๊ป˜ ์ž‘๋™์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•œ ๊ฒฐํ•ฉ๋œ ๋น„์ „์„ ์ œ์•ˆ
  • Decorators๋Š” ์ด๋ฏธ ์ •์˜๋œ ํด๋ž˜์Šค, ํ•จ์ˆ˜, ๋ณ€์ˆ˜์˜ ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•˜๊ธฐ ์•Š๊ณ , ๊ธฐ๋Šฅ์„ ์ถ”๊ฐ€ํ•˜๋Š” ๊ฒƒ์— ์œ ์šฉํ•จ
  • ๋ฉ”๋ชจ์ด์ œ์ด์…˜, ์ ‘๊ทผ ์ œ์–ด, ์ธ์ฆ, ๊ณ„์ธก, ํƒ€์ด๋ฐ ์ฒ˜๋ฆฌ, ๋กœ๊น…, ์†๋„ ์ œํ•œ ๋“ฑ์— ์‚ฌ์šฉ๋œ๋‹ค.

Decorators ์‹ค์šฉ์„ฑ

JavaScript์—์„œ๋Š” Decorators๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์ง€๋งŒ TypeScript์—์„œ Decorators๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ž˜์„œ Node.js Framework nestjs์™€ Front-end Framework Angular์—์„œ๋Š” ๊ณต์‹์ ์œผ๋กœ ์‚ฌ์šฉ ์ค‘์ด๋‹ค.

์ฝ”๋“œ ์‚ฌ์šฉ ์˜ˆ์‹œ

  • @defineElement: ์ปค์Šคํ…€ ์—˜๋ ˆ๋ฉ˜ํŠธ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ธฐ๋Šฅ
  • @bound: ๋””๋ฐ”์šด์Šค ์ฒ˜๋ฆฌ ๊ธฐ๋Šฅ
  • @observed: ํ•„๋“œ๋ฅผ ๊ฐ์‹œํ•˜๋ฉฐ ๋ณ€๊ฒฝ ์‹œ ์ž๋™์œผ๋กœ render()๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ธฐ๋Šฅ
@defineElement('num-counter')
class Counter extends HTMLElement {
  @observed #x = 0;

  @bound
  #clicked() {
    this.#x++;
  }

  constructor() {
    super();
    this.onclick = this.#clicked;
  }

  connectedCallback() { this.render(); }

  @bound
  render() {
    this.textContent = this.#x.toString();
  }
}