kgneng2 / blokg

blog
MIT License
0 stars 0 forks source link

javascript decorator #40

Open kgneng2 opened 3 years ago

kgneng2 commented 3 years ago

https://medium.com/@yeon22/javascript-javascript-decorator-6cd79f9f71d9

const testObj = {
  num: 10,
  name: 'Hi'
};
console.log(Object.getOwnPropertyDescriptor(testObj, 'num');
// {configurable: true, enumerable: true, value: 10, writable: true}
Object.defineProperty(testObj, 'num', {
  writable: false,
  value: 4
});
testObj.num = 40;
console.log(testObj.num); // {num: 4, name: 'Hi'}

자바스크립트 데코레이터 함수에는 3가지 인자가 전달됩니다.

  1. 현재 인스턴스 객체의 클래스
  2. 데코레이터를 적용할 속성 이름(문자열)
  3. 해당 속성의 설명자 객체

decorator function

function readOnly(target, propertyName, descriptor) {
  return {
    ...descriptor,
    writable: false,
  };
}

example

class Test {
  @readOnly num = 10; // 또는 데코레이터를 속성 바로 위에 정의해도 동일하게 동작합
니다.
  constructor(name) {
    this.name = name;
  }
}
const testObj = new Test('Hello');
testObj.num = 50;
console.log(testObj); // { name: 'Hello', num: 10 }
kgneng2 commented 3 years ago

확장

참고.