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();
}
}