There are two types of data in JS:
1. Base type: number, String, Boolean, Null, Undefined
2. Complex Type: Object, Array
deep and shallow copies are only for complex types of data , because the definition of the underlying type data will re-open up new memory.
A shallow copy of the memory address, just add a pointer to the existing memory, when multiple data sharing a memory space; a deep copy is a new pointer and opens up memory space, and the new pointer points to the new memory.
Shallow copy:
var a={
Name: ' Wangjing ',
Sex: ' Woman ',
Age: ' 25 '
};
var b = a ;
B.name = ' white child painting ';
Console.log (A.name); White draw--------------Shallow copy: Copy the memory address, pointer to the same memory space, modify one of the others will also change
Modifying the property value of object B, the property value of object A also changes, this is the shallow copy (the same is the array)
Deep copy:
var c = {}; Do not write Var C; Will error
function Extend (A, b) {
For (Var prop in a) {
B[prop]=a[prop];
}
}
Extend (A,C);
C.name = "Hu";
Console.log (A.name); White draw--------------Deep copy: New memory, new pointer to new memory space modify one of them will not affect the other data
The following code resolves a deep copy
function Extend (A, B) {for (Var prop in a) {//Determine if is the base data type if (typeof a[prop] = = = "Object") {B[prop] = (A[prop].constructor = = = Array)? []: {};//object and array difference processing extend (A[prop], B[prop]);} else {B[prop] = A[prop];}}}
Deep copy and shallow copy of JavaScript