deep copy

var copyObjectDeep = function (target) {
  var result = {};
  if (typeof target === 'object' && target !== null) {
    for (var prop in target) {
      result[prop] = copyObjectDeep(target[prop]);
    }
  } else {
    result = target;
  }
  return result;
};

var user = {
  name: 'Jason',
  urls: {
    portfolio: 'http://github.com/abc',
    blog: 'http://blog.com',
    facebook: 'http://facebook.com/abc',
  },
};

var user2 = copyObjectDeep(user);

user.name = 'Mraz';
user2.name = 'Bbo';

user.urls.blog = 'google';
user2.urls.facebook = 'meta';

console.log(user);
console.log(user2);

// JSON 활용 깊은 복사

var copyObjectViaJSON = function (target) {
  return JSON.parse(JSON.stringify(target));
};

var obj = {
  a: 1,
  b: {
    c: null,
    d: [1, 2],
    func1: function () {
      console.log(3);
    },
  },
  func2: function () {
    console.log(4);
  },
};

var obj2 = copyObjectViaJSON(obj);

console.log(obj);
console.log(obj2);

© 2021. All rights reserved.

----------Powered by Hydejack----------

woobaeh