深度克隆类实例JavaScript [英] Deep clone class instance JavaScript

查看:75
本文介绍了深度克隆类实例JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种在保留所有原型原型的同时深度克隆JS类实例的方法.

I'm trying to figure out a way to deep clone a JS class instance while preserving all the prototypes down the chain.

我已经了解了如何深化克隆和对象:

I've seen how to deep clone and object:

JSON.parse(JSON.stringify(instance))

我已经看到了如何制作类实例的浅表副本:

And I have seen how to make a shallow copy of a class instance:

Object.assign( Object.create( Object.getPrototypeOf(instance) ), instance)

但是我的问题是,有没有办法深克隆一个类的实例?

But my question is, is there a way to deep clone an instance of a class?

推荐答案

没有万无一失的方法来克隆JS中所有可能的对象类型,尤其是当它包含对其他对象的引用时.通用克隆参数不知道克隆中的对象引用是否应该包含相同的引用(例如,公共父对象),或者是否也需要克隆对象,我也有一个引用.不可能一概而论,因为它实际上取决于对象的实现.

There is no foolproof way to clone all possible types of objects in JS, particularly if it contains references to other objects. A generic cloning argument doesn't know whether an object reference in the clone should contain the same reference (such as a common parent) or whether it needs to clone the object i has a reference too also. It isn't possible to know that generically as it really depends upon the implementation of the object.

如果有对对象的循环引用,例如父级到子级和子级到父级,则它会变得更加复杂.

If there are circular references to objects such as parent to child and child to parent, it gets even more complicated.

再举一个例子,假设一个对象作为其构造函数的一部分,它将创建一个唯一的对象ID,将该ID注册到某些服务中,然后将该ID存储在其实例数据中.通用克隆机制无法知道创建新对象需要逻辑(生成新ID并将其注册到某些服务中).这种类型的逻辑将必须通过特定于知道该做什么的对象的代码来完成.

As another example, imagine an object that as part of its constructor, it creates a unique object ID, registers that id with some service and then stores the ID in its instance data. There's no way way for a generic clone mechanism to know that logic (generating a new ID and registering it with some service) is required to make a new object. That type of logic would have to be done by code specific to that object that knows what to do.

再举一个例子,构造函数可能会创建闭包(可以访问私有信息),而闭包是无法从外部复制的.

As another example, a constructor might create closures (with access to private information) that there is no way to duplicate from the outside.

再举一个例子,构造函数可能会将方法绑定到自己的实例,而泛型克隆将不需要这样做.

As another example, a constructor might bind methods to its own instance that a generic clone would have no idea it needed to do.

克隆对象的最佳方法是使用对象实现中内置的代码,该代码知道如何克隆自身,例如在对象本身上添加.clone()方法(或随便命名),并拥有该对象支持复制自身.然后,它可以对任何实例数据做正确的事情,只有对象实现本身才能知道如何处理所有可能类型的实例数据.

The best way to clone an object is with code built into the implementation of the object that knows how to clone itself such as adding a .clone() method (or name it whatever you want) on the object itself and have the object support making a duplicate of itself. Then, it can do the right thing with any instance data which only the object implementation itself can know how to handle all possible types of instance data.

这篇关于深度克隆类实例JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆