Shallow copy and deep copy

Shallow copy vs deep copy

  • Shallow copy: Creates a new object with an exact copy of the original object’s property value, the value of the base type if the property is of a primitive type, and the memory address of the reference type if the property is of a reference type.If one object changes this address, it affects another object.
  • Deep copy: to make a full copy of an object out of memory, create a new area of heap memory to store the new object, andModifying the new object does not affect the original object.

The assignment

// Object assignment

let obj1 = {

    name : 'A'.

Arr: [1, 2, 3], 4].

};

let obj2 = obj1;

obj2.name = "B";

Obj2. Arr [1] = [5, 6];

console.log('obj1',obj1); // obj1 {name: 'B', arr: [1, [5, 6], 4]}

console.log('obj2',obj2); // obj2 {name: 'B', arr: [1, [5, 6], 4]}

Copy the code

Shallow copy

/ / shallow copy

let obj1 = {

    name : 'A'.

Arr: [1, 2, 3], 4].

};

let obj3 = shallowClone(obj1);

obj3.name = "B";

Obj3. Arr [1] = [5, 6]; // Old and new objects still share the same memory



// This is a shallow-copy method

function shallowClone(source) {

    var target = {};

    for (var i in source) {

        if (source.hasOwnProperty(i)) {

            target[i] = source[i];

        }

    }

    return target;

}

console.log('obj1',obj1); // obj1 {name: 'A', arr: [1, [5, 6], 4]}

console.log('obj3',obj3); // obj3 {name: 'B', arr: [1, [5, 6], 4]}

Copy the code

Deep copy

/ / copy

let obj1 = {

    name: 'A'.

Arr: [1, 2, 3], 4].

};

let obj4 = deepClone(obj1);

obj4.name = "B";

Obj4. Arr [1] = [5, 6]; // The new object does not share memory with the original object



// This is a deep-copy method

function deepClone(obj) {

    if (obj === null) return obj; 

    if (obj instanceof Date) return new Date(obj);

    if (obj instanceof RegExp) return new RegExp(obj);

    if(typeof obj ! = ="object"return obj;

    let cloneObj = new obj.constructor();

    for (let key in obj) {

      if (obj.hasOwnProperty(key)) {

// Implement a recursive copy

        cloneObj[key] = deepClone(obj[key]);

      }

    }

    return cloneObj;

}

console.log('obj1',obj1); // obj1 {name: 'A', arr: [1, 2, 3], 4]}

console.log('obj4',obj4); // obj4 {name: 'B', arr: [1, [5, 6], 4]}

Copy the code

Shallow copy implementation

  1. Object.assign() : copies any number of source objects’ own enumerable attributes to the target Object and returns the target Object.
let obj1 = { person: {name: "Messi", age: 33}, club: 'Barcelona' };

let obj2 = Object.assign({}, obj1);

obj2.person.name = "Suarez";

obj2.club = "Atletico Madrid ';

console.log(obj1); // { person: { name: 'Suarez', age: 33 }, club: 'Barcelona' }

Copy the code
  1. The _.clone method of the lodash library
var _ = require('lodash');

var obj1 = {

    a: 1,

    b: { f: { g: 1 } },

    c: [1, 2, 3]

};

var obj2 = _.clone(obj1);

console.log(obj1.b.f === obj2.b.f); // true

Copy the code
  1. Expansion operator…
let obj1 = { name: 'Messi', address:{ x: 100, y: 100 } } 

let obj2 = {... obj1}

obj1.address.x = 200;

obj1.name = 'Suarez';

console.log('obj2', obj2); // obj2 { name: 'Messi', address: { x: 200, y: 100 } }

Copy the code
  1. Array.prototype.concat()
let arr = [ 1, 3, { username: 'Messi'}];

let arr2 = arr.concat();

arr2[2].username = 'Suarez';

console.log(arr); // [ 1, 3, { username: 'Suarez'}]

Copy the code
  1. Array.prototype.slice()
let arr = [1, 3, { username: 'Messi'}];

let arr3 = arr.slice();

arr3[2].username = 'Suarez'

console.log(arr); // [ 1, 3, { username: 'Suarez'}]

Copy the code

Deep copy implementation

  1. JSON.parse(JSON.stringify()): Json.stringify converts the object into a JSON string, and json.parse parses the string into an object. As you go, a new object is created, and the object opens up a new stack for deep copy (functions and regex cannot be handled).
let arr1 = [1, 3, { username: 'Messi' }, function(){} ];

let arr2 = JSON.parse(JSON.stringify(arr1));

arr2[2].username = 'Suarez';

Copy the code
  1. The _. CloneDeep method of the lodash library
var _ = require('lodash');

var obj1 = {

    a: 1,

    b: { f: { g: 1 } },

    c: [1, 2, 3]

};

var obj2 = _.cloneDeep(obj1);

console.log(obj1.b.f === obj2.b.f); // false

Copy the code
  1. JQuery. The extend () method
$.extend(deepCopy, target, object1, [objectN]) //true, is the deep copy

Copy the code