Shallow copies and deep copies are relative to reference types.
JS has two major types of value types (basic data types) and reference types (Object,function,array);
Value types are saved on the stack, and reference types are saved on the heap.
A shallow copy is simply the address of a copy object.
//shallow copy of ObjectvarAA = {name: ' AA ', age:26, DX: {dxname: ' Dxname ', dxage:24 } };varBB =Aa
Console.log (BB===AA); //true //here represents the same address pointed to Console.log (bb . name); //AABb.name= ' BB '; Console.log (Aa.name); //BBConsole.log (Bb.name);//BB
The object is saved above the heap, and the AA variable simply saves the address of the AA object 6ff65a1c;
Bb=aa just give the address 6ff65a1c to BB, so point to the same object, so changed the Bb.name,aa.name also followed the change.
A deep copy is a copy of the object completely.
varA = {name: ' AA ', age:26, DX: {dxname: ' Dxname ', dxage:24 } }; varb =NewObject (); B.name=A.name; B.age=A.age; B.DX= {};//open up a space and then copyB.dx.dxname=A.dx.dxname; B.dx.dxage=A.dx.dxage; B.name= ' BB '; B.dx.dxage= 30; Console.log (A===b); Console.log (A); Console.log (a); Console.log (' B '); Console.log (b);
Because B is getting a copy of a, so change B will not affect the A
varDeepcopy =function(source) {//Deep copy function varresult = {}; for(varKeyinchsource) { //recursively copies the value of type object, regardless of the function typeResult[key] =typeof(Source[key]) = = = ' object '?deepcopy (Source[key]): Source[key]; } returnresult; }
varA = {name: ' AA ', age:26, DX: {dxname: ' Dxname ', dxage:24 } }; /*var b = new Object (); B.name = A.name; B.age = A.age; B.DX = {}; Open up a space and then copy the B.dx.dxname=a.dx.dxname; B.dx.dxage=a.dx.dxage;*/ varb=Deepcopy (a); B.name= ' BB '; B.dx.dxage= 30; Console.log (A===b); Console.log (A); Console.log (a); Console.log (' B '); Console.log (b);
Shallow and deep copies of arrays
//Array Shallow copyvararr = ["One", "one", "three"]; varArrto =arr; arrto[1] = "Test"; Document.writeln ("Original value of the array:" + arr + "<br/>");//Export: Original value of array: One,test,threeDocument.writeln ("New value of the array:" + Arrto + "<br/>");//Export: New value for array: One,test,three //Array Deep CopyvarARR2 = ["One", "one", "one", "three"]; varArrtoo = Arr.slice (0); arrtoo[1] = "Set Map"; Document.writeln ("Original value of the array:" + arr2 + "<br/>");//Export: Original value of array: One,two,threeDocument.writeln ("New value of the array:" + Arrtoo + "<br/>");//Export: New value for array: One,set map,three
JS Shallow copy (address reference) and deep copy (clone)