Shallow copy

Direct assignment

const obj = {name: 'zjx'};
const obj2 = obj;
obj.name = 'zjx2';
console.log(obj); // {name: 'zjx2'}
console.log(obj2); // {name: 'zjx2'}
Copy the code

Deep copy

To iterate over

function copyObj(obj) {
  let newObj = {};
  for (var key in obj) {
    newObj[key] = obj[key];
  }
  return newObj;
}
const obj = {name: 'zjx'};
const obj2 = copyObj(obj);
obj.name = 'zjx2';
console.log(obj); // {name: 'zjx2'}
console.log(obj2); // {name: 'zjx'}
Copy the code

Through json.stringify and json.parse

In this way, functions in the object will not be copied, resulting in function loss.

const obj = {name: 'zjx'.test: function () {console.log('0')}};
const obj2 = JSON.parse(JSON.stringify(obj));
obj.name='zjx2';
console.log(obj); // {name: 'zjx2', test: function () {console.log('0')}}
console.log(obj2); // {name: 'zjx'}
obj2.test(); // obj2.test is not a function
Copy the code

ES6 extension operator

const obj = {name: 'zjx'};
constobj2 = {... obj}; obj.name ='zjx2';
console.log(obj); // {name: 'zjx2'}
console.log(obj2); // {name: 'zjx'}
Copy the code