table of Contents:
1: shallow copy
2: deep copy
1: shallow copy
< Script > // shallow copy: copy is the copy, the equivalent of all of the contents of an object, the copy to another object, direct copy, or that is the address of an object to another object they point to the same, there are between two objects in common property or method, may be used var OBJ1 = { Age: 10 , Sex: " M " , CAR: [ " Benz " , " BMW " , " Tesla " , " Alto " ] }; // another object var obj2 = {}; // write a function, function: copy attribute of one object to another object, the shallow copy // all the properties of a replicated object b subject to the function Extend (A, B) { for ( var Key in A) { B [Key] = A [Key]; } } Extend (OBJ1, obj2); obj2.sex = " F " ; console.dir (obj2); // beginning this object is empty object console.dir (OBJ1); // have attributes the console.log (OBJ1 == obj2); </ Script >
Shallow copy: Schematic
2: deep copy
< Script > // Deep Copy: Copy or Copy, depth: all the attributes of an object or method, to find and open a corresponding one of the other objects in space, one of a stored into another object. Var OBJ1 = { Age: 10 , Sex: " M " , CAR: [ " Benz " , " BMW " , " Tesla " , " Alto " ], Dog: { name: " rhubarb " , Age: . 5 , Color: "Black and white " } }; Var obj2 = {}; // null object // through a function implemented, all data objects in a deep copy of the object b to function Extend (a, b) { for ( var Key in a) { / / first obtaining a value of each attribute of the object var Item = a [Key]; // Analyzing this attribute value is not an array IF (Item the instanceof the array) { // if the array, then add a new object in the b attribute, and the attribute value is an array b [Key] = []; // call this method to a copy of a property of the array to the object a b value of this property in the object array Extend (Item, b [Key]); } the else IF (Item the instanceof Object) { // Analyzing this value is not an object type // If the object type, then add an attribute in the object b is an empty object b [Key] = {}; // call the function again, the value of a property of the object a copy of a property of the object to object b object Extend (Item, b [Key]); } the else { / / If the value is an ordinary data copied directly to the object attribute b b [Key] = Item; } } } Extend (OBJ1, obj2); console.dir (OBJ1); console.dir (obj2); </script>