Javascript는 value 타입의 변수들의 경우 별개의 메모리 공간에 생성되지만 객체인 경우에는 reference타입이라 참조 복사가 된다.
복사 처리를 해주려면 그 객체가 가지고 있는 모든 property를 하나 하나 복사하고 상속 구조도 고려하여 복사 처리를 해줘야 된다.
http://stackoverflow.com/questions/728360/copying-an-object-in-javascript
위 Q&A 사이트에 많은 방법들이 나와 있는데 두가지만 언급한다.
첫번째 방법 :
function clone(obj){
var clonedObjectsArray = [];
var originalObjectsArray = []; //used to remove the unique ids when finished
var next_objid = 0;
function objectId(obj) {
if (obj == null) return null;
if (obj.__obj_id == undefined){
obj.__obj_id = next_objid++;
originalObjectsArray[obj.__obj_id] = obj;
}
return obj.__obj_id;
}
function cloneRecursive(obj) {
if (null == obj || typeof obj == "string" || typeof obj == "number" || typeof obj == "boolean") return obj;
// Handle Date
if (obj instanceof Date) {
var copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
var copy = [];
for (var i = 0; i < obj.length; ++i) {
copy[i] = cloneRecursive(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
if (clonedObjectsArray[objectId(obj)] != undefined)
return clonedObjectsArray[objectId(obj)];
var copy;
if (obj instanceof Function)//Handle Function
copy = function(){return obj.apply(this, arguments);};
else
copy = {};
clonedObjectsArray[objectId(obj)] = copy;
for (var attr in obj)
if (attr != "__obj_id" && obj.hasOwnProperty(attr))
copy[attr] = cloneRecursive(obj[attr]);
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
var cloneObj = cloneRecursive(obj);
//remove the unique ids
for (var i = 0; i < originalObjectsArray.length; i++)
{
delete originalObjectsArray[i].__obj_id;
};
return cloneObj;
}
두번째 방법 :
function ObjectCopy(obj)
{
return JSON.parse(JSON.stringify(obj));
}
위 방법은 json.org 사이트의 json2.js를 include 해줘야 한다. (퍼포먼스 측면에서 느릴수 있음.)
'프로그램개발 > ClientSide(JavaScript,Angular,Vue)' 카테고리의 다른 글
함수형 프로그래밍이란 무엇인가? (0) | 2016.01.07 |
---|---|
자바스크립트엔진, 폴리글랏 엔진으로 진화한다 (0) | 2015.06.26 |
제가 느꼈던 front-end를 갈아엎어야 한다는 판단이 섰을때 (0) | 2015.06.10 |
자바스크립트 개발 가이드 번역사이트 (0) | 2015.05.20 |
자바스크립트는 왜 웹개발 핵심 기술로 성장했나 (0) | 2015.04.13 |