In JS, we usually create a JSON object with VAR to store the data conveniently.
var template = {
User: ' Zhang ',
Password: ",
tem:[' label 1 ', ' label 2 ']
}
This approach is generally used as a standard data format.
Let's start with a shallow clone.
Then we look at the following code
function SetObject (obj) {
var newObj = {};
for (var i in obj) {
Newobj[i] = Obj[i]
}
return NEWOBJ;
}
var tem2 = setobject (template);
Tem2.user= "Shaw";
Tem2.password = "123";
Tem2.tem.push (' music ');
var tem3 = setobject (template);
Tem3.user= "Liu MoU";
Tem3.password = "123456";
Tem3.tem.push (' Sports ');
Console.log (TEM2)//
- "Label 1"
- 1:"label 2"
- 2:"Music "
- 3:"Sport "
Console.log (TEM3)//
- "Label 1"
- 1:"label 2"
- 2:"Music "
- 3:"Sport "
The tem2 tem is seen by printing as an array of tem3 tem.
This is very well understood, because a simple copy of the object, if one of the objects is a reference variable, this happens, because the reference variable is stored in memory address, so in fact, the operation is the same piece of memory, resulting in the same array content.
Let's take a look at the following situation
function SetObject (obj,newobj) {
var newObj = NEWOBJ | | {};
for (var i in obj) {
if (typeof obj[i] = = ' object ') {
Newobj[i] = (Obj[i].constructor = = = = Array)? [] : {}
SetObject (Obj[i],newobj[i])
}else{
Newobj[i] = Obj[i]
}
}
return NEWOBJ;
}
var tem2 = setobject (template);
Tem2.user= "Shaw";
Tem2.password = "123";
Tem2.tem.push (' music ');
var tem3 = setobject (template);
Tem3.user= "Liu MoU";
Tem3.password = "123456";
Tem3.tem.push (' Sports ');
Console.log (TEM2)//tem2.tem
Array (3)
- 0:" Label 1 "
- 1< Span class= "Object-properties-section-separator" >:" label 2 "
- 2:" music "
- length:3
Console.log (TEM3)//Tem3.tem
-
- Array (3)
- 0:"label 1"
- 1:"label 2"
- 2:"Sport "
- Length:3
Deep cloning is in the cloning of the time to determine whether the type of the property is a reference variable, if it is a recursive method to let it in a layer to copy themselves.
This is the depth of cloning, in fact, JS is a method of inheritance.
On deep cloning and shallow cloning in JS