Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

A shallow copy simply creates a new object and copies the values of the original object’s primitive type, while a reference data type copies only one layer of properties. If one object changes the address in this memory, it must affect the other object

Deep copy is different, the reference for complex data types, an object from memory a complete copy of a copy to the target object, and open up a whole new from heap memory space to store the new object, will not change the original object is modified and a new object, these two objects are mutually independent and is not affected, thoroughly implement the separation on the memory

Deep copy can be implemented in two ways:

  • Using JSON. Parse (JSON. Stringify ());
  • Manual implementation

JSON. Parse (JSON. Stringify ())

Json.stringify () is the simplest deep-copy method, which serializes an object into a JSON string, converts the contents of the object into a string, and then generates a new object from the JSON string using json.parse ()

const obj = {
  name: 'nordon'.info: {
    age: 18}};// One line of code implements deep copy
const copyObj = JSON.parse(JSON.stringify(obj));
Copy the code

While implementing deep copy using json.parse (json.stringify ()) is simple and convenient, it has some API-level features:

  • If the value of the copied object is function, undefined, or symbol, the key/value pair will disappear in the string serialized by json. stringify
    • undefined, any function andsymbolAs an object property valueJSON.stringify()Skip (ignore) serializing them
  • Convert value if anytoJSON()Function, which returns what value it serializes and ignores the values of other attributes
  • Copying the Date reference type becomes a string
  • Unable to copy non-enumerable properties
  • Unable to copy the object’s prototype chain
  • Copying the RegExp reference type becomes an empty object
  • Object containing NaN, Infinity, and -infinity will result in NULL JSON serialization
  • Unable to copy objects that contain circular references (objects that refer to each other in an infinite loop), an error is thrown

Manual implementation

Json.parse (json.stringify ()) has some shortcomings in implementing deep copy, which is recommended for careful use in business development. Therefore, we need to manually implement a version of deep copy

Parse (json.stringify ()) (json.parse ())) (json.stringify ())) (json.parse ()))

The details are commented out in the code

// Check if it is a reference type
const isComplexDataType = (obj) = > {
	return (typeof obj === "object" || typeof obj === "function") && obj ! = =null
}

const deepClone = function (obj, hash = new WeakMap(a)) {
	// The date object returns a new date object
	if (obj.constructor === Date) return new Date(obj);
	
	The regular object returns a new regular object directly
	if (obj.constructor === RegExp) return new RegExp(obj); 

	// If the loop is referenced, use weakMap
	if (hash.has(obj)) return hash.get(obj);

	let allDesc = Object.getOwnPropertyDescriptors(obj);
	// Walks through the properties of all keys of the passed argument
	let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);

	// Inherit the prototype chain
	hash.set(obj, cloneObj);

	for (let key of Reflect.ownKeys(obj)) {
		cloneObj[key] =
			isComplexDataType(obj[key]) && typeofobj[key] ! = ="function"
				? deepClone(obj[key], hash)
				: obj[key];
	}
	return cloneObj;
};
Copy the code