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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With