简体   繁体   English

深度合并两个类实例

[英]Deep merge two class instances

How do I properly deep merge ( lodash like) two ES6 class instances ?我如何正确地深度合并(类似lodash )两个ES6 类实例
The resulting object has to be an actual instance of the same class and its properties should be a deep merge of the two instances' properties.结果对象必须是同一类实际实例,其属性应该是两个实例属性的深度合并。


If there is no need to create a new instance, the following will do如果不需要创建新实例,则执行以下操作

_.merge(instance1, instance2)

This will deep merge instance2 properties into instance1 while preserving the prototype.这将在保留原型的同时将instance2属性深度合并到instance1


If the merged instance should be a brand new object it is still achievable:如果合并的实例应该是一个全新的对象,它仍然可以实现:

let newInstance = Object.assign(Object.create(Object.getPrototypeOf(o1)), _.merge(o1, o2));

This will create a new object which is an instance of the same class o1 is and will deep merge into it the properties of o1 and o2 .这将创建一个新对象,该对象是同一个类o1的实例,并将深度合并o1o2的属性。
This approach, however, has some caveats, for example (from here ):但是,这种方法有一些注意事项,例如(来自此处):

It's hardly possible if the instance was created with heavy use of closures in the constructor function.如果实例是在构造函数中大量使用闭包创建的,那几乎是不可能的。 We may never now which internal values were set, and how to reproduce such a setup.我们可能永远不会知道设置了哪些内部值,以及如何重现这样的设置。

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

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