I do not know when to start, the front circle has emerged a new word: Object depth cloning. Looks like very tall appearance, actually is not fresh, in our actual project development, you may have already used, just because of the profound character, some originally very simple things by some seemingly professional vocabulary slightly modified, became mysterious.
Why do you want to make a deep clone of an object first? Let me make a guess: you will sometimes think that JS's built-in object document is too long, then you might do this:
Copy Code code as follows:
var d = document;
D.by = function (ID) {
return d.getElementById (ID);
};
D.by (' id '). innerHTML = ' Hello Sentsin ';
The above code simplifies the document.getElementById and adds an by member method to the original document object, and you can verify your judgment by the state value returned by Document.hasownproperty (' by '). Let's look at one of the following examples.
Copy Code code as follows:
var person = {name: ' Yin Xin ', profession: ' Front-End development ', place: ' Hangzhou '};
var Newperson = person;
Newperson.age = ' 24 ';
Console.log (person);
Result: {name: ' Yin Xin ', profession: ' Front-End development ', place: ' Hangzhou ', age:24}
Thus, when an object is simply passed to a new variable, it simply adds an alias to the object. This means that the original object key value changes by manipulating the alias. The problem is that sometimes we want Newperson to be completely independent of the person, and there is no sync between each other, so you need to generate a copy, see examples:
Copy Code code 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),//Serialization Object
newobj = Json.parse (str); Restores
} 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];
Perform a deep clone
var newobj = cloneobj (obj);
var newarr = cloneobj (arr);
To delete a member of a new cloned object
Delete newobj.a;
Newarr.splice (0,1);
Console.log (obj, arr, newobj, newarr);
Results: {a:0, b:1, c:2}, [0, 1, 2], {b:1, c:2}, [1, 2];
This is called object cloning. But there are a couple of places to explain. The JSON object in code and its member methods Stringify and parse belong to the ECMASCRIPT5 specification, which is responsible for converting an object, including an array object, into a string, and restoring, which enables a deep copy of the object. Then for the low-level browser (IE), copy the array, you can use Newobj.concat (obj), and ordinary objects, just simply enumerate the assignment good.