deep copy vs shallow copy

deep copy

$.extend(), set to true is a deep copy

var x = {
    a: 1,
    b: { f: { g: 1 } },
    c: [ 1, 2, 3 ]
};

var y = $.extend({}, x),          //shallow copy
    z = $.extend(true, {}, x);    //deep copy

y.b.f === x.b.f       // true
z.b.f === x.b.f       // false

Native implementation:
Deep copy is different. It not only copies each attribute of the original object one by one, but also recursively copies the objects contained in each attribute of the original object by means of deep copy (note recursion, the reference type has a multi-layer structure) to the new object

function deepCopy(p,c){
    var i;
    c = c||{};
    for(i in p){
        if(p.hasOwnProperty(i)){
            if(typeof(p[i])==="object"){
                c[i] = Array.isArray(p[i])?[]:{};
                deepCopy(p[i],c[i]);
            }else{
                c[i] = p[i];
           }
        }
    }
    return c;
}

Specifically for deep copying of JSON objects: For deep copying of pure JSON data objects, using the  parse sum  stringify method of JSON global object to achieve deep copying is also a simple and convenient method. However, using this method will have some hidden pits. The only objects it can handle correctly are Number, String, Boolean, Array, and flat objects, that is, those data structures that can be directly represented by json.

function jsonClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}
var clone = jsonClone({ a:1 });

Shallow copy method

var obj = a: 1 , arr: [ 2 , 3 ]};
var shallowObj = shallowCopy (obj);

function shallowCopy(src) {
  var dst = {};
  for (var prop in src) {
    if (src.hasOwnProperty(prop)) {
      dst[prop] = src[prop];
    }
  }
  return dst;
}

Object.assign(...)

var y = $.extend({}, x), //shallow copy


Reference
https://github.com/LiuL0703/blog/issues/19
http://jerryzou.com/posts/dive-into-deep-clone-in-javascript/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324896634&siteId=291194637