I don’t know when it started, but a new word appeared in the front-end circle: object depth cloning. It looks very tall, but it is not new in fact. You may have used it in our actual project development, but because of the profoundness of Chinese characters, some originally simple things become mysterious by slightly modified by some seemingly professional vocabulary.
First of all, why do you need to deep clone an object? Please allow me to make a guess: you sometimes think that the built-in object document of js is too long, then you might do this:
The code copy is as follows:
var d = document;
d.by = function(id){
return d.getElementById(id);
};
d.by('id').innerHTML = 'hello sentsin';
The above code simplifies document.getElementById, and also adds a by member method to the original document object. You can verify your judgment by using the status value returned by document.hasOwnProperty('by'). Let’s take a look at the following example.
The code copy is as follows:
var person = {name: 'Xianxin', profession: 'front-end development', place: 'Hangzhou'};
var newPerson = person;
newPerson.age = '24';
console.log(person);
//Result: {name: 'Xianxin', profession: 'front-end development', place: 'Hangzhou', age: 24}
It can be seen that when an object is simply passed to a new variable, it is simply an alias to the object. This means that the original object key value will change through the operation on the alias. But the problem is that sometimes we want newPerson to be completely independent of person and there is no synchronization relationship between each other, so we need to generate a copy, please see the example:
The code copy is as follows:
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
} else {
for(var i in obj){
newobj[i] = typeof obj[i] === 'object' ?
cloneObj(obj[i]) : obj[i];
}
}
return newobj;
};
//test
var obj = {a: 0, b: 1, c: 2};
var arr = [0, 1, 2];
//Execute deep cloning
var newobj = cloneObj(obj);
var newarr = cloneObj(arr);
//Remove member deletion of cloned new object
delete newobj.a;
newarr.splice(0,1);
console.log(obj, arr, newobj, newarr);
//Result: {a: 0, b: 1, c: 2}, [0, 1, 2], {b: 1, c: 2}, [1, 2];
This is the so-called object cloning. But there are a few things that need to be explained. The JSON object and its member methods stringify and parse in the code belong to the ECMAScript5 specification. They are responsible for converting an object (including array objects) into strings and restoring them, thereby realizing deep copying of the object. So for low-level browsers (such as IE), if you copy arrays, you can use newobj.concat(obj), and ordinary objects can simply enumerate and assign values.