In depth cloning of JavaScript objects

  • 2020-03-30 04:30:56
  • OfStack

I don't know when it started, but a new word came out of the front loop: object deep cloning. In fact, it is not new. You may have used it in our actual project development. However, due to the extensive and profound Chinese characters, some simple things become mysterious after being modified by some seemingly professional words.

Why deep clone an object in the first place? Allow me to make a guess: you must sometimes think that js's built-in object document is too long, so you might do something like this:


var d = document;
d.by = function(id){
    return d.getElementById(id);
};
d.by('id').innerHTML = 'hello sentsin';

The above code simplifies document.getelementbyid and adds a member method of by to the original document object. You can verify your judgment by the status value returned by document.hasownproperty ('by'). Let's do another example.


var person = {name: ' Good heart ', profession: ' The front-end development ', place: ' hangzhou '};
var newPerson = person;
newPerson.age = '24';
console.log(person);
//Results: {name: 'xian xin', profession: 'front-end development', place: 'hangzhou', age: 24} < br / >


var cloneObj = function(obj){
    var str, newobj = obj.constructor === Array ? [] : {};
    if(typeof obj !== 'object'){
        return;
    } else if(window.JSON){
        str = JSON.stringify(obj), //Serialized object
        newobj = JSON.parse(str); //Restore < br / >     } else {
        for(var i in obj){
            newobj[i] = typeof obj[i] === 'object' ?
            cloneObj(obj[i]) : obj[i];
        }
    }
    return newobj;
};
//The test < br / > var obj = {a: 0, b: 1, c: 2};
var arr = [0, 1, 2];
//Perform deep cloning
var newobj = cloneObj(obj);
var newarr = cloneObj(arr);
//
is deleted as a member of the cloned new object delete newobj.a;
newarr.splice(0,1);
console.log(obj, arr, newobj, newarr);
//Results: {a: 0, b: 1, c: 2} to [0, 1, 2], 2} {b: 1, c:, [1, 2]; < br / >

This is called object cloning. But there are a few things to explain. The JSON object in the code and its member methods stringify and parse are part of the ECMAScript5 specification, which are responsible for converting an object (including an array object) to a string, and restoring, respectively, to achieve a deep copy of the object. For low-level browsers, such as IE, to copy an array, you can use newobj.concat(obj), while for ordinary objects, you can simply enumerate and assign values.


Related articles: