[JS] JS deep copy

Transfer part: https://www.cnblogs.com/renbo/p/9563050.html

Mode 1:

var syb = Symbol('obj');
var person = {
name :'tino',
say: function(){
console.log('hi');
},
ok: syb,
un: undefined
}
var copy = JSON.parse(JSON.stringify(person))
// copy
// {name: "tino"}

Option 2:

function deepCopy(obj) {
      var result = Array.isArray(obj) ? [] : {};
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (typeof obj[key] === 'object' && obj[key]!==null) {
            result[key] = deepCopy(obj[key]);   //递归复制
          } else {
            result[key] = obj[key];
          }
        }
      }
      return result;
    }

Another scenario:

After converting the object serialization in JS into a class ClassA JSON, like the JSON object (JS in addition to the basic type String are other Object) is converted into objects of that class of ClassA (This method can be invoked ClassA a) requires the assignment of field by field.

As the increase in a class ClassA method setObject (obj), in which method this.a = obj.a, such a field of an assignment field. kind of hard.

 

Guess you like

Origin www.cnblogs.com/tigerhsu/p/11460073.html