Study/JavaScript

[자스 한스푼 ep.3] 프로퍼티 attribute - 불변 객체

life-of-jibro 2022. 12. 5. 17:39

앞선 ep.02에서 살펴본 변경 방지 메서드들은 얕은 복사만을 막는 수준에 불과했다. 따라서 중첩 객체에 대해서는 변경을 허용하게 되는 문제가 있었다. 이를 해결하기 위해 객체를 값으로 가지는 모든 프로퍼티에 대해 재귀적으로 Object.freeze 메서드를 호출하는 방법을 사용하여 중첩 객체에 대하여도 객체 동결을 수행할 수 있다.

 

function deepFreeze(target) {
  if (target && typeof target === 'object' && !Object.isFrozen(target)) {
    Object.freeze(target);
    Object.keys(target).forEach((key) => deepFreeze(target[key]));
  }
  return target;
}

const person = {
  name: 'Lee',
  address: { city: 'Seoul' },
};

console.log(Object.isFrozen(person)); // false
console.log(Object.isFrozen(person.address)); // false

deepFreeze(person);

console.log(Object.isFrozen(person)); // true
console.log(Object.isFrozen(person.address)); // true

person.address.city = 'Busan';
console.log(person); // { name: 'Lee', address: {city: 'Seoul'} }

 

[ 참고 자료 ]

모던 자바스크립트 딥다이브 (이웅모 저) / 16장 프로퍼티 어트리뷰트 -  pp. 232 - 233