Talking about Shallow Copy and Deep Copy

Shallow copy

As the name suggests, only the first layer of copy is made, Insert picture description here
then this cc will not be copied, so when we use the stretch operator to shallow copy, the Insert picture description here
Insert picture description here
result can be imagined, we change the value of ee, but dd will also be affected, Because only the first layer is copied.
Then when we modify the first layer, the
Insert picture description here
Insert picture description here
result is as shown in the figure, and it will not be affected.
Shallow copy implementation methods, such as the extension operator, and the use of Object.create(). If you don’t understand, you can go to the rookie station,
as shown in
Insert picture description here
Object.create. The Insert picture description here
simple version of these things is implemented, you just need to remember to return. An object whose __proto__ points to the first parameter you pass in. The second parameter Insert picture description here
is to return all the attribute descriptions of dd. You can check the official website by yourself, which is equivalent to creating a new object. This new object has all the methods of dd, and its __proto__ points to the same as dd's __proto__ points. So I copied it.

Deep copy, as the name implies, is that no matter how many layers there are, I copy one by one, and the copied object will not affect the original object in any way.

There are two types. The first method is
JSON.parse(JSON.stringfy(obj)).
This method also has shortcomings. It ignores Undefined, cannot serialize functions, and cannot resolve circularly referenced objects.
The second is to encapsulate a function yourself.
Insert picture description here
The idea is very simple. Just go in and judge whether it is an array object. If yes, traverse and judge whether the son is his own, because for in will traverse to the continued attribute, and then judge that the son is not null and the son is an object or an array. At this point, the recursion continues.
If it is not, it is easy to handle, just assign the value directly.
Insert picture description here

Change the value of d to see if there is any change
Insert picture description here

As you can see, it only affected myself. The deep copy is successful. It is recommended to write the function a few more times to understand it, not as good as bad writing

Guess you like

Origin blog.csdn.net/lin_fightin/article/details/114690717