불변 객체
자바스크립트에서 객체의 상태(즉, 프로퍼티의 값)가 생성 후 변경될 수 없는 객체를 의미
객체의 불변성을 유지한다는 것
사용하는 경우
- 객체에 변화를 가해도 원본이 그대로 남아있어야 하는 경우
- 특히, 메모리(데이터베이스)에 저장 되어 있는 객체를 다루는 경우
- 불변객체를 이용하여 상태변화를 추적해야하는 경우
사용하는 이유
- 오류감소 : 객체의 상태가 변경되지 않기 때문에 예기치 않은 상태 변경으로 인한 버그감소
- 성능최적화 : 복제나 비교를 위한 조작을 단순화 할 수 있고 성능 개선에도 도움
불변객체를 만드는 방법
Object.freeze() [ ref ]
const user= {
name: "JJ",
age : 38,
address : {
nation: "Korea",
city: "JinJu"
}
}
Object.freeze(user) // 상위레벨에 있는 것만 보호
user.name = "KK"
user.address.city = "Seoul"
console.log(user.name) // "JJ"
console.log(user.address.city) // "Seoul"
// deep freeze
const deepFreeze = obj => {
Object.keys(obj).forEach(prop => {
if (typeof obj[prop] === 'object') deepFreeze(obj[prop]);
});
return Object.freeze(obj);
};
Spread 연산자 [ ref ]
- 새로운 객체를 만들 때 사용
const obj1 = { type: 'data' }
const arr1 = [1, 2, 3]
const obj2 = { ...obj1, subtype: 'stuff' } // 원본 유지하면서 새로운 프로퍼티 추가
const arr2 = [ ...arr1, 'cheese' ] // 새로운 요소 추가
const data = { type: 'data', age: 55 }
const data2 = { ...obj1, age: data.age + 1 }// 원본 유지하면서 기존의 데이터 변경
꼭 변환을 해야한다면 깊은 복사를 하여 복사본을 변경을 하는 것을 추천한다.
// 스프레드 연산자
const originalArray = [ 1,2, 3]
const deepCopyArray = [ ... originalArray]
const user= {
name: "JJ",
age : 38,
address : {
nation: "Korea",
city: "JinJu"
}
}
// 1 단으로만 이루어진 객체에서는 가능
// spread
const copyUser = { ...user}
copyUser.name = "N"
copyUser.address.city = "Seoul"
// 원본 user 가 변경되었는지 확인
console.log(user.name) // "JJ" : 변경 안됨
console.log(user.address.city) // "Seoul" : "JinJu" 에서 "Seoul" 로 변경
// Object.assign 도 동일
const copyUserObjectAssign = Object.assign({}, user);
/* 1단 이상인 경우 */
// JSON 이용
const userCopyJSON = JSON.parse(JSON.stringify(user));
// 재귀함수 이용
function CopyObjectDeeply(target) {
var result = {};
if (typeof target === "object" && target !== null) {
for (var prop in target) {
result[prop] = copyObjectDeep(target[prop]); // 재귀적 호출
}
} else {
result = target;
}
return result;
};
const userCopyFunction = CopyObjectDeeply(user)
참고자료
https://developer.mozilla.org/ko/docs/Glossary/Deep_copy
https://www.freecodecamp.org/news/immutable-javascript-improve-application-performance/
https://www.freecodecamp.org/news/javascript-immutability-frozen-objects-with-examples/
https://dev.to/glebec/four-ways-to-immutability-in-javascript-3b3l
'프로그래밍 > JavaScript' 카테고리의 다른 글
[ JS ] 프라미스와 async / await : 콜백 (0) | 2024.06.03 |
---|---|
[ JS ] 원시값, 참조값, 얕은 복사, 깊은 복사 (0) | 2024.05.20 |
[ JS ] Promise.allSettled 사용하는 이유 (0) | 2024.05.06 |
[ JS ] Promise.all() 사용하는 이유 (0) | 2024.05.06 |
[ JS ] Promise 설명 (0) | 2024.05.05 |