简体   繁体   English

如何在JS中创建对象的可变且不可变的副本

[英]How to create mutable AND immutable copy of object in JS

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. 似乎Object.freeze()也通过引用冻结对象。

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. mutableCopyimmutableData指向JS堆上的同一对象。

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. 当然,您可以将新对象设为可变副本,而将旧对象设为不变的副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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