Without using any additional libraries, how I can I create an immutable copy of an object and retain a mutable copy.
var mutableCopy = immutableData;
Object.freeze(immutableData);
mutableCopy.newProp = 'mutated!';
console.log(mutableCopy.hasOwnProperty('newProp')); // false
It seems that Object.freeze()
also freezes objects by reference.
How can I create a mutable and immutable copy of an object?
var objCopy = {};
for ( var propKey in objToClone )
objCopy[ propKey ] = objToClone[ propKey ];
And object.freeze whichever you prefer. If you've a more complex/deeper object and need to mutate those deeper properties, I'd probably just use something hacky like
var objCopy = JSON.parse( JSON.stringify( objToClone ) );
You are slightly right in this is a problem of pass-by-reference vs pass-by-value. In reality, the pass-by-reference occurs in the first line. Both mutableCopy
and immutableData
point to the same object on the JS heap.
What you should do is make a new object that is a duplicate of the old one. Then, freezing the new object will leave the old one as a mutable copy while preventing modifications.
var newObj = {}
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
}
Object.freeze(newObj);
You can, of course, make the new object the mutable copy and the old one the immutable one should you so choose.
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.