Object

Object.defineProperty()

2021년 12월 26일 https://junilhwang.github.io/TIL/Javascript/Design/Vanilla-JS-Store/#_1-object-defineproperty-이해하기

이를 구현하기 위해선 먼저 **Object.defineProperty (opens new window)**라는 API에 대해 알아야 한다.

MDN 문서에 나와있는 설명은 다음과 같다.

객체에 직접 새로운 속성을 정의하거나 이미 존재하는 속성을 수정한 후, 그 객체를 반환합니다.

사실 이런 설명을 보면 이해되지 않는 경우가 대부분일 것이다. 그래서 구구절절 늘어놓기 보단, 역시 코드로 이해하는 게 더 빠를 것이다.

let a = 10;
const state = {};
Object.defineProperty(state, 'a', {
  get () {
    console.log(`현재 a의 값은 ${a} 입니다.`)
    return a;
  },
  set (value) {
    a = value;
    console.log(`변경된 a의 값은 ${a} 입니다.`)
  }
});

console.log(`state.a = ${state.a}`);
state.a = 100;

Untitled

이렇게 Object.defineProperty(object, prop, descriptor) 는 객체에 어떤 변화가 생기거나 객체를 참조할 경우 우리가 원하는 행위를 중간에 집어넣을 수도 있다.

const state = {
  a: 10,
  b: 20,
};

const stateKeys = Object.keys(state);

for (const key of stateKeys) {
  let _value = state[key];
  Object.defineProperty(state, key, {
    get () {
      console.log(`현재 state.${key}의 값은 ${_value} 입니다.`);
      return _value;
    },
    set (value) {
      _value = value;
      console.log(`변경된 state.${key}의 값은 ${_value} 입니다.`);
    }
  })
}

console.log(`a + b = ${state.a + state.b}`);

state.a = 100;
state.b = 200;

Untitled

Array Methods

Array.prototype.find()