I don’t know when a new word started popping up in the front-end circle: object deep cloning. It may seem very lofty, but in fact it is not new. In our actual project development, you may have already used it. However, due to the broad and profound Chinese characters, some originally simple things are slightly obscured by some seemingly professional vocabulary. Add embellishments and it becomes mysterious.
Why deep clone an object in the first place? Please allow me to make a guess: You must sometimes think that the built-in object document of js is too long, then you may do this:
The above code simplifies document.getElementById, and also adds a by member method to the original document object. You can verify your judgment through the status value returned by document.hasOwnProperty('by'). Look at the following example.
It can be seen that when an object is simply passed to a new variable, it only adds an alias to the object. This means that by operating on the alias, the original object key value will change. But the problem is that sometimes we want newPerson to be completely independent of person and there is no synchronization relationship between them, so we need to generate a copy, please see the example:
//Test
var obj = {a: 0, b: 1, c: 2};
var arr = [0, 1, 2];
//Perform deep cloning
var newobj = cloneObj(obj);
var newarr = cloneObj(arr);
//Delete members of the new object after cloning
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 called object cloning. However, there are a few things that need explanation. The JSON object in the code and its member methods stringify and parse belong to the ECMAScript5 specification. They are respectively responsible for converting an object (including array objects) into a string and restoring it, thereby realizing a deep copy of the object. So for low-level browsers (such as IE), if you copy an array, you can use newobj.concat(obj), and for ordinary objects, you can simply enumerate and assign values.