The principle of

Create a new object of your own to accept the object values you want to copy or reference again. If the object property is a primitive data type, the value of the primitive type is copied to the new object. But if the property is a reference data type, the copy is the address in memory, and if one object changes the address in memory, the other object must be affected.

implementation

1. object.assign

Syntax: object. assign(target,… Sources);

The object. assign loop iterates over the properties of the original Object and assigns them to the corresponding properties of the target Object by copying them.

Note: it does not copy the object’s inherited properties; It does not copy the object’s non-enumerable properties; You can copy a Symbol attribute;

2. Extend the operator mode

Let cloneObj = {… obj };

The extension operator has the same drawback as object.assign, that is, it performs almost the same function as shallow copies, but it is more convenient to use the extension operator for shallow copies if the attributes are values of primitive types.

3. Concat copies arrays

The concat method of arrays is a shallow copy, so when concating an array with a reference type, you need to be careful to modify the attributes of the elements in the original array, because this will affect the concatenated array.

Note: Concat, however, can only be used for shallow copies of arrays, which can be very limited.

4. Slice copies arrays

The syntax is: arr.slice(begin, end);

The slice method returns a new array object that uses the first two arguments of the method to determine the start and end times of the original array and does not affect or alter the original array.

Note: The Slice method is also somewhat limited because it only works with array types.

limit

Shallow copy copies only one layer of objects. If there is nesting of objects, shallow copies are useless. Therefore, deep copy is born to solve this problem, it can solve the problem of multi-layer object nesting, complete copy.

expand

Implement a shallow copy yourself

The general idea is divided into two points: make a basic copy of the base type; Create a new store for reference types and copy a layer of object properties.