본문 바로가기

JavaScript

[JavaScript] 객체의 변경을 방지하는 방법

자바스크립트에서 객체는 변경 가능한 값이므로 재할당없이 직접적으로 변경이 가능하다. 이를 방지하기 위한 많은 방법이 있는데, 불변성을 확립해주는 라이브러리를 사용한다던지, Object 메서드를 이용하여 객체를 복사하여 변경하는 방법, 그리고 객체의 변경을 애초에 방지하는 방법이 있다.

 

 

오늘은 얉은 복사를 통해 객체의 변경을 방지하는 방법을 알아보고자 한다.

 

 

1. Object.preventExtensions()

 

- 객체의 확장을 금지하는 메서드.

 

const animals = { name: "Lion", age: 12 };

console.log(Object.isExtensible(animals)); // 확장이 가능한 지 묻는 Object 메서드

Object.preventExtensions(animals);

console.log(Object.isExtensible(animals));

animals.age = 15; // ?????

delete animals.age;

console.log(animals);

 

 

preventExtensions()를 통해 extensible의 값을 false로 변경하게 해서 확장이 불가능하게 한다. 단 주의할 점은 확장만 불가능 한거지 프로퍼티를 삭제할 순 있다.

 

 

 

 

2. Object.seal();

 

말 그대로 객체를 밀봉하는 함수이다. 프로퍼티의 추가 및 삭제, 어트리뷰터 재정의 등이 모두 금지되고 오직 읽기와 쓰기만 가능하다.

 

해당 객체가 밀봉이 됐는지 안됐는지는 Object.isSealed()로 확인이 가능하다.

 

 

 

 

const person = { name: "Jang" };

Object.seal(person);

console.log(Object.isSealed(person));

 

3. Object.freeze();

 

 

이 메서드는 객체를 동결해버린다. 프로퍼티 추가 및 삭제 어트리뷰트 재정의 금지는 물론이고 프로퍼티 값 갱신까지 금지하기 때문에 읽기만 가능하다.

 

 

const footballTeam = { name: "chelsea" };

Object.freeze(footballTeam);

console.log(Object.isFrozen(footballTeam));

console.log(Object.getOwnPropertyDescriptors(footballTeam));

footballTeam.name = "Man.UTD"; // ignored
delete footballTeam.name; // ignored

Object.defineProperty(footballTeam, 'name', { configurable: true }); // TypeError