简体   繁体   中英

How to make a deep copy of Object with get and set operators in JS

I hope you'll help me.

I want to make a deep copy of this object User.

function clone(obj) {
    if (null == obj || "object" != typeof obj)
        return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr))
            copy[attr] = obj[attr];
    }
  return copy;
}

var User = {
    _firstName: 'robert',

    get firstName() {
        return this._firstName;
    },
    set firstName(val) {
        this._firstName = val;
    },

    affFirstName: function() {
        console.log(this._firstName);
    },
};

console.log(User);
var User2 = clone(User);    
console.log(User2);

This function clone doesn't work (see fiddle for example)

This copy creates new variable with the name of get and set.

Set and get Operators are not copied.

But the function affFirstName() is well copied.

Do you have a solution ?

In ES5, you can use Object.getOwnPropertyDescriptor to get a copy of the getters and setters that may exist on an object.

You can then pass those descriptors to Object.defineProperty to recreate them on a new object.

Note that if those getters or setters rely on lexically scoped variables the new clone will share those variables with the original object. The new object will not get its own copy of those variables.

function clone(obj) {
  if (null == obj || "object" != typeof obj)
    return obj;
  var copy = obj.constructor();
  for (var attr in obj) {
    if (obj.hasOwnProperty(attr)) {
      if (Object.getOwnPropertyDescriptor(obj, attr).value instanceof Object) {
        copy[attr] = clone(obj[attr]);
      }
      else {
        Object.defineProperty(copy, attr, Object.getOwnPropertyDescriptor(obj,attr));
      }
    }
  }
  return copy;
}

The corrected clone function to make a deep copy with operators get and set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM