Talk about deep replication in Javascript

  • 2020-03-30 04:28:59
  • OfStack

In javascript, all assignments between object variables are addressable, and some students may ask which ones are objects. Examples might be good:


typeof(true)    //"boolean"
typeof(1)       //"number"
typeof("1")     //"string"
typeof({})      //"object"
typeof([])      //"object"
typeof(null)    //"object"
typeof(function(){})  //"function"

So in fact, the main objects we need to deal with in deep replication are object objects, non-object objects as long as the direct normal assignment is good. My idea of js deep replication is:

Traversing all the properties of the object,
If the property is "object", special handling is required,
If the object is special and is an array, create a new array and copy the elements deep into the array
If the object object is a non-array object, simply recursively call the deep copy method on it.
If it is not "object", just copy it normally.

Here is my implementation:


Object.prototype.DeepCopy = function () {
  var obj, i;
  obj = {};   for (attr in this) {
    if (this.hasOwnProperty(attr)) {
      if (typeof(this[attr]) === "object") {
        if (this[attr] === null) {
          obj[attr] = null;
        }
        else if (Object.prototype.toString.call(this[attr]) === '[object Array]') {
          obj[attr] = [];
          for (i=0; i<this[attr].length; i++) {
            obj[attr].push(this[attr][i].DeepCopy());
          }
        } else {
          obj[attr] = this[attr].DeepCopy();
        }
      } else {
        obj[attr] = this[attr];
      }
    }
  }
  return obj;
};


Object.defineProperty(obj, attr, Object.getOwnPropertyDescriptor(this, attr));

To replace the


obj[attr] = this[attr];

The advantage of implementing this method directly on object.prototype is that all objects inherit from it. The downside is that some libraries also overwrite objects, so sometimes there are conflicts. This is something to be aware of. The specific use method is as follows:


Object.prototype.DeepCopy = function () { ... }
var a = { x:1 };
var b = a;
var c = a.DeepCopy();
a.x = 2;
b.x = 3;
console.log(a.x);   //3
console.log(b.x);   //3
console.log(c.x);   //1

So that's deep replication, but now that we've talked about deep replication, we want to talk about shallow replication, so let's just briefly summarize the similarities and differences between them.

Shallow copy (shadow clone): only copies the basic type of the object, the object type, which still belongs to the original reference.
Deep copy (deep clone): not only copies the basic class of the object, but also copies the object in the original object.


Related articles: