일반 object clone

황제낙엽 2011.07.08 17:44 조회 수 : 5045

sitelink1 http://blog.imaginea.com/deep-copy-in-javascript/ 
sitelink4 http://1 
extra_vars4 ko 
extra_vars6 sitelink1 
 

Some of you might have come across this issue. When you make a copy of an object and try to change the values of the new instance, it reflects in the original one too. Well I heard this not only applies to JavaScript, but also to most other object oriented languages; not sure though.

Here is a case:

Problem
//original object definition
var oOriginal = {
    memNum: 1,                                        // number
    memStr: "I am a string",                          // string
    memObj: {
        test1: "Old value"                            // we'll test
    },
    memArr: [                                         // array with object members
        "a string",                                   // simple string element
        {                                             // an object
            test2: "Try changing me"                  // we'll test
        }
    ]
};

//test 1
var oCopy = oOriginal;                                // normal copy

oCopy.memObj.test1 = "New value";                     // Problem
                                                      // - will reflect in oOriginal

alert(oOriginal.memObj.test1);                        // will show "New value"

//test 2
oCopy.memArr[1].test2 = "I am changed";               // Problem
                                                      // - will reflect in oOriginal

alert(oOriginal.memArr[1].test2);                     // will show "I am changed"

 

 

Here the problem is, the objects are never copied, only their references are. So what’s the solution? Iterate through all members of the original object, create the same members for target object and then assign corresponding values. And while doing so, we can’t forget array of objects.

We’ll add this simple line at the very top to help us detect Array objects. It basically adds our own custom extension to the Array class.

To recognize Array type objects
<html>
<head>
<title>Deep Copy in JavaScript</title>
<script language="javascript" type="text/javascript">
    Array.prototype.__isArray = true;
</script>
.
.

 

 

Now, here is the generic method that will help in iterating through all (type of) members of our original object and copy them one-by-one regardless of the depth of the object structure:

Solution
var ObjectHandler = {
    //public method
    getCloneOfObject: function(oldObject) {
        var tempClone = {};

        if (typeof(oldObject) == "object")
            for (prop in oldObject)
                // for array use private method getCloneOfArray
                if ((typeof(oldObject[prop]) == "object") &&
                                (oldObject[prop]).__isArray)
                    tempClone[prop] = this.getCloneOfArray(oldObject[prop]);
                // for object make recursive call to getCloneOfObject
                else if (typeof(oldObject[prop]) == "object")
                    tempClone[prop] = this.getCloneOfObject(oldObject[prop]);
                // normal (non-object type) members
                else
                    tempClone[prop] = oldObject[prop];

        return tempClone;
    },

    //private method (to copy array of objects) - getCloneOfObject will use this internally
    getCloneOfArray: function(oldArray) {
        var tempClone = [];

        for (var arrIndex = 0; arrIndex <= oldArray.length; arrIndex++)
            if (typeof(oldArray[arrIndex]) == "object")
                tempClone.push(this.getCloneOfObject(oldArray[arrIndex]));
            else
                tempClone.push(oldArray[arrIndex]);

        return tempClone;
    }
};

 

 

Now we’ll perform the same two tests mentioned in the ‘Problem’ block using this new helper – ObjectHandler

Test
//test 1
var oCopy = ObjectHandler.getCloneOfObject(oOriginal);

oCopy.memObj.test1 = "New value";

alert(oOriginal.memObj.test1);                        // will show "Old value"

//test 2
oCopy.memArr[1].test2 = "I am changed";

alert(oOriginal.memArr[1].test2);                     // will show "Try changing me"

 

 

In general, this solution is often referred to as "Deep Copy".

번호 제목 글쓴이 날짜 조회 수
246 [Gemini] ajax 와 fetch 의 차이 황제낙엽 2025.01.04 3419
245 [검토 완료] 디바이스 카메라로 촬영한 사진을 서버에 업로드하기 샘플 황제낙엽 2024.11.21 3987
244 브라우저에서 이미지를 편집(crop 등) 할 수 있는 오픈소스 Cropper.js 황제낙엽 2024.11.16 3842
243 [ChatGPT] json data 의 정렬 [1] 황제낙엽 2024.07.23 3352
242 DOMContentLoaded 이벤트와 window.onload 이벤트 황제낙엽 2024.07.15 3669
241 fetch() 사용 예제들 황제낙엽 2024.07.09 3380
240 [Copilot] Vanilla JavaScript에서 외부 스크립트 파일에 정의된 함수들을 로드 황제낙엽 2024.06.21 3758
239 [Copilot] ES6 모듈(module) 문법 황제낙엽 2024.06.21 3805
238 [Copilot] JSON 객체 내부 데이터를 순회하면서 조회하는 코드 황제낙엽 2024.06.02 3270
237 [Copilot] JavaScript로 서버에 특정 값을 POST 방식으로 전달하고 응답을 기다리지 않고 바로 종료 황제낙엽 2024.05.31 3615
236 json 데이터 내의 변수명에 prefix 로 type 표현하기 황제낙엽 2024.04.15 3361
235 fetch() 함수 사용 예제 file 황제낙엽 2023.11.23 3605
234 현재 document 의 host 와 port 를 얻는 방법 황제낙엽 2023.10.03 4209
233 (Bard) FileReader 로 여러개의 파일을 read 하는 법 file 황제낙엽 2023.08.23 3660
232 How to build a file upload service with vanilla JavaScript file 황제낙엽 2023.08.22 3715
231 (Bard) JavaScript로 JSON 배열을 작성하는 방법 황제낙엽 2023.08.21 3672
230 모바일 브라우저에서 file input element 를 이용하여 여러장의 이미지를 서버에 전송하려 할때 [1] 황제낙엽 2023.08.21 3703
229 navigator.mediaDevices 황제낙엽 2023.08.21 3798
228 Barcode Detection API 황제낙엽 2023.08.06 3854
227 정규식을 이용한 이메일 검증 스크립트 file 황제낙엽 2023.06.25 2894