λ°μ½λ μ΄ν°(Decorator)
μμ§ JSμ μ μ κΈ°λ₯μ΄ μλλ€. ECMA TC39μ νμ€ν μ μ°¨λ₯Ό μ§ννκ³ μλ€.
Babelμ μ¬μ©ν΄μ μ¬μ©ν μ μλ€.
μ ν¨μλ₯Ό λ°ννμ¬ μ λ¬λ ν¨μ λλ λ©μλμ λμμ μμ νλ ν¨μ
ν¨μλ₯Ό μΌκΈ μλ―ΌμΌλ‘μμ κΈ°λ₯μ μ§μνλ λͺ¨λ μΈμ΄λ λ°μ½λ μ΄ν°λ₯Ό ꡬνν μ μλ€.
νμ΄μ¬ μμ
νμ΄μ¬μ λ°μ½λ μ΄ν°κ° JSμ λ°μ½λ μ΄ν° μλ λ°©μλ³΄λ€ λ¨μνμ¬ μ€λͺ νκΈ° μ’λ€.
def cashify(fn): def wrap(): print("$$$$") fn() print("$$$$") return wrap @cashifydef sayHello(): print("hello!") sayHello() # $$$$ # hello! # $$$$
μμ± μ€λͺ μ#
JS κ°μ²΄λ νλ‘νΌν°κ° μκ³ , κ° νλ‘νΌν°λ κ° λΏλ§ μλλΌ μ¨κ²¨μ§ μ 보λ€μ κ°λλ€ .
Object.getOwnPropertyDescriptor/Object.getOwnPropertyDescriptorsλ₯Ό μ¬μ©ν΄ μ μ μλ€.
const oatmeal = { viscosity: 20, flavor: 'Brown Sugar Cinnamon',}; console.log(Object.getOwnPropertyDescriptor(oatmeal, 'viscosity')); /*{ value: 20, writable: true, enumerable: true, configurable: true,}*/κ°μ²΄μ μ κ·Όμ νλ‘νΌν°λ
valueμwritableμ΄ μλ λμ μgetκ³Όsetμ΄λΌλ ν¨μκ° μλ€.
λ°μ½λ μ΄ν° μμ±λ²#
- JS λ°μ½λ μ΄ν° ν¨μμλ μΈ κ°μ§ μΈμκ°μ λ¬λλ€.
target: νμ¬ μΈμ€ν΄μ€ κ°μ²΄μ ν΄λμ€key: λ°μ½λ μ΄ν°λ₯Ό μ μ©ν μμ± μ΄λ¦(λ¬Έμμ΄ )descriptor: ν΄λΉ μμ±μ μ€λͺ μ κ°μ²΄ - κ°μ²΄μ λ©μλλμμ±μ κΎΈλ―Έλ €λ©΄μλ‘μ΄ μμ± μ€λͺ μλ₯Όλ°νν΄μΌ νλ€. - μμ±μ μ½κΈ°μ μ©μΌλ‘ λ§λλ λ°μ½λ μ΄ν°
function readOnly(target, key, descriptor) { return {...descriptor, writable: false};}
class Oatmeal extends Porridge { @readOnly viscosity = 20;
constructor(flavor) { super(); this.flavor = flavor; }}TypeScript#
tsconfig.jsonμμexperimentalDecoratorsμ»΄νμΌλ¬ μ΅μ μ νμ±νν΄μΌ νλ€.