티스토리 뷰

Javascript

Immutable object 만들기

cs09g 2020. 6. 10. 17:12
반응형

기본적으로 Javascript의 원시 타입(Undefined, Null, Boolean, Number, String 등)을 제외한 모든 객체는 mutable하다.

즉 생성된 이후에 언제든 변경될 수 있다.

 

이런 mutable한 객체를 immutable하게 변경하는 것도 가능하다. 다음의 두 옵션을 활용해볼 수 있다.

 

1. Object.defineProperty를 통한 설정

let customObj = {};
Object.defineProperty(customObj, "newKey", {value: "newValue"});

위와 같이 Object.defineProeprty 메소드를 사용하면 newKey의 값은 읽기 전용이되어 수정하는 것이 불가해진다.

이 메소드는 writable 옵션을 포함하고 있는데 기본 값이 false이다.

하지만 새로운 프로퍼티를 추가하는 것은 얼마든 가능하며, {writable: true} 옵션을 설정할 경우 수정이 가능해진다.

let customObj = {};
Object.defineProperty(customObj, "newKey", {value: "newValue"});

customObj.anotherKey = "anotherValue"; // 새로운 프로퍼티를 추가할 수 있다.
// customObj = {newKey: "newValue", anotherKey: "anotherValue"}

customObj.anotherKey = "theOtherValue"; // 수정도 가능하다.
// customObj = {newKey: "newValue", anotherKey: "theOtherValue"}

customObj.newKey = "anotherValue"; // 하지만 writable: false인 프로퍼티의 경우 암묵적으로 무시된다.
// customObj = {newKey: "newValue"}

Object.defineProperty(customObj, "theOtherKey", {value: "theOtherValue", writable: true});
customObj.theOtherKey = "newValue"; // 수정이 가능하다.
// customObj = {theOtherKey: "newValue"}

 

2. Object.freeze 를 통한 설정

let customObj = {};
customObj.newKey = "newValue";
Object.freeze(customObj);

위와 같이 freeze를 사용하게 되면 객체가 말그대로 얼어 붙는다. 추가하거나 삭제, 수정 모두가 불가해진다.

let customObj = {};
customObj.newKey = "newValue";
Object.freeze(customObj);

// 모든 편집 작업이 암묵적으로 무시된다.
customObj.anotherKey = "anotherValue"; // 추가할 수 없다.
// customObj = {newKey: "newValue"}

delete customObj.newKey; // 제거할 수 없다.
// customObj = {newKey: "newValue"}

customObj.newKey = "anotherValue"; // 수정할 수 없다.
// customObj = {newKey: "newValue"}

 

 

특정 프로퍼티를 immutable하게 하려면 Object.defineProperty를, 객체 자체를 immutable하게 하려면 Object.freeze를 활용하면 된다.

반응형
댓글