In general, shallow copy is used to describe the cloning of objects in JavaScript.

A shallow copy is a clone of a reference to an object, so it ends up pointing to the object in the heap. If either the copy or the original object modifies the object, the data in the heap will change because their Pointers point to the same object in the heap.

Deep copy, on the other hand, directly clones the parent object in the heap memory, eventually creating a new object in the heap memory, independent of the parent object. Deep-copied objects are independent of, but consistent with, the parent object. When the deep copy is complete, changes to the parent object do not affect the new object from the deep copy, and vice versa.

A shallow copy copies only one layer, and a deep copy copies multiple layers.

Shallow copy implementation:

A:

Let obj = {name: "Tom, age: 20, MSG: {job: 'coder,}, arr: [1, 2, 3],}; let newObj = {}; for(let k in obj) { newObj[k] = obj[k]; } console.log(newObj); //{name: 'Tom', age: 20, MSG: {... }}, arr: [1, 2, 3] the console. The log (newObj = = = obj); //false console.log(newObj.msg === obj.msg); //true console.log(newObj.arr === obj.arr); //true newObj.name = 'Jack'; console.log(newObj.name); //'Jack' console.log(obj.name); //'Tom'Copy the code

Method 2:

Let obj = {name: "Tom, age: 20, MSG: {job: 'coder,}, arr: [1, 2, 3],}; let newObj = {}; Object.assign(newObj,obj); console.log(newObj === obj); //false console.log(newObj.msg === obj.msg); //true console.log(newObj.arr === obj.arr); //true newObj.name = 'Jack'; console.log(newObj.name); //'Jack' console.log(obj.name); //'Tom'Copy the code

Three:

Let obj = {name: "Tom, age: 20, MSG: {job: 'coder,}, arr: [1, 2, 3],}; let newObj = {... obj}; console.log(newObj); //{name: 'Tom', age: 20, MSG: {... }}, arr: [1, 2, 3] the console. The log (newObj = = = obj); //false console.log(newObj.msg === obj.msg); //true console.log(newObj.arr === obj.arr); //true newObj.name = 'Jack'; console.log(newObj.name); //'Jack' console.log(obj.name); //'Tom'Copy the code

Deep copy implementation:

Deep copy is copying multiple layers, using recursive functions. As for the function copy, because the function is an object to achieve the same function, so whether deep or shallow copy, copy is the pointer to the function object, that is, its address.

Let obj = {name: 'Tom', age: 20, MSG: {job: 'coder',}, arr: [1,2,3], fn: function(value) {return value; }}; function deepCopy(item) { let o = item instanceof Array ? [] : {}; for(let k in item) { if(typeof item[k] ! = 'object') o[k] = item[k]; else o[k] = deepCopy(item[k]); } return o; } let newObj = deepCopy(obj); console.log(newObj === obj); //false console.log(newObj.msg === obj.msg); //false console.log(newObj.arr === obj.arr); //fals console.log(newObj.fn(1)); / / 1Copy the code