Welcome to pay attention to mygithub

Base and reference types

Basic type: A segment of data stored in stack memory that can be accessed and modified directly because it is stored by value

Reference type: Objects stored in heap memory. A variable in stack memory holds a pointer to an address in heap memory. When accessing a reference type, the object’s address pointer is fetched from the stack, and then the required data is fetched from the heap.

Value and address passing

Basic types are stored by value and can be accessed directly

The reference type is the address stored in the stack, the need to access the corresponding value according to the address is the address

var a = [1, 2, 3, 4, 5] var b = a; Var c = a [0] alert / / 1, 2, 3, 4, 5 (b) alert (c) / / / / change the value 1 b [4] = 6 c = 7 alert (a) [4] / / 6 alert (a [0]) / / 1Copy the code

When a is assigned to B, it actually copies the address of A to B in stack memory. At this time, BOTH A and B access objects with the same address. Therefore, modifying B [4] directly changes the value of objects in heap memory, and both A and B access this value at the same time, and a and B are associated. C is not associated with a or B by assigning the value of an object in the heap directly

So to put it simply, deep copies must be passed by value, and shallow copies must be passed by address

Shallow copy

var a = { key1:"11111" } function Copy(p) { var c = {}; For (var I in p) {c[I] = p[I]; } return c; } a.key2 = [' x ',' x ']; var b = Copy(a); b.key3 = '33333'; alert(b.key1); //1111111 alert(b.key3); //33333 alert(a.key3); //undefinedCopy the code

Because a.key2 is a reference type, the copy of A. key2 is passed by address, which causes the value of B. key2 to change, because a.key2 is passed by address. Since A and B are related, this copy is a shallow copy

Deep copy

Change the code to this:

var a = { key1:"11111" } function Copy(p) { var c = {}; For (var I in p) {c[I] = p[I]; } return c; } var b = Copy(a); b.key1 = '33333'; alert(a.key1); //1111111 alert(b.key1); / / 33333Copy the code

This copy is a deep copy because it is a basic copy and is passed by value

In this case, we know the structure of the current object. If we do not know the structure of the current object, how to make a deep copy? Deep copy can be done recursively

function copy(a, b) { var c = c || {} for(var i in a) { if(typeof a[i] == 'object') { if(a[i].constructor == Array) { copy(a[i], c[i]) } else if(a[i].constructor == Object) { copy(a[i], c[i]) } } else { c[i] = a[i] } } return c } var a = { key1: '11111', key2: [1, 2, 3, 4, 5]} var b = copy (a, b) b.k ey2,2,2,2,2 [2] = alert (a.k ey2) / / 1, 2, 3, 4, 5 alert (b.k ey2) / / 2,2,2,2,2Copy the code

Both a and B are copied by value, so there is no correlation between A and B, so this is a deep copy



References:

http://www.cnblogs.com/lsgxeva/p/7985583.html