js differs in shallow copy and implementations of the deep copy

The basic data types can be understood as Chaozuo Ye, reference data types can be understood as write two names on a job of this. Deep copy and shallow copy is for reference data types (personal understanding)

Article is from   https://www.jianshu.com/p/a8dc699e9534

1. Assignment and shallow copy What is the difference?

  obj1 raw data

  obj2 assignment data

  shallow copy data obj3

 

He went on to say shallow copy.

Why change the assignment obj3 resulting object obj2 and shallow copy obtained in Language ) of the second and third value of the attribute values ( Language is an array, which is a reference type ). Results are output, can be seen, either modify the assignments and the resulting object obj2 obtained obj3 shallow copy of the original data will change.

[Shallow copy copy because only one object attribute, a reference type does not include data objects is inside. So there will be changes obj3 shallow copy obtained in reference types, the original data will be changed. ] Sentence is simple to understand:

Shallow copy is a copy of a layer, in addition to a copy of the object reference type, (the beginning of the other mentioned basic data types ) are transmitted directly to the value, it has its own memory space

Deep copy: copying the object A to the object B, the object B includes sub inside,
shallow copy: copying the object B to the object A, but does not include sub-objects inside B

 

Shallow copy

1. destructuring assignment

 

 

 

 

2.ES6 method of Object.assign

 

Object.assign is ES6 new function. Object.assign () method can be any of a plurality of source object itself may be enumerated attribute copy to the target object, the target object and then returns. However Object.assign () shallow copy is performed, the copy attribute is a reference to an object, rather than the object itself.

 

Object.assign (target, ... sources)
parameters:

 

target: the target object.
sources: any of the plurality of source objects.
Returns: the target object will be returned.

 

 

 

Deep copy

After reading comprehension shallow copy, you can know: that is a deep copy of the object and all child objects object copy.
The next change is to explore how an object is a deep copy?

1, with JSON.stringify the object into a string, the string JSON.parse then transformed into a new object (using JSON).

 

Downside: it will abandon the constructor of the object. After that is a deep copy, no matter what the subject of the original constructor, after a deep copy will become Object. So only suitable for flat objects Number, String, Boolean, Array of

2, recursive copy

 Or use in the Object.create es6 () method







 

Guess you like

Origin www.cnblogs.com/ymm-notes-blog/p/12668444.html