如何克隆JavaScript ES6类实例 [英] How to clone a javascript ES6 class instance
问题描述
如何使用ES6克隆Javascript类实例.
How do I clone a Javascript class instance using ES6.
我对基于jquery或$ extend的解决方案不感兴趣.
I'm not interested in solutions based on jquery or $extend.
我见过很多关于对象克隆的讨论,这些讨论表明问题非常复杂,但是使用ES6时,会出现一个非常简单的解决方案-我将其放在下面,看看人们是否认为它令人满意.
I've seen quite old discussions of object cloning that suggest that the problem is quite complicated, but with ES6 a very simple solution presents itself - I will put it below and see if people think it is satisfactory.
有人建议我的问题重复.我看到了这个答案,但它已有7年历史,并且使用ES6之前的js涉及非常复杂的答案.我建议我的问题(允许使用ES6)有一个非常简单的解决方案.
edit: it is being suggested that my question is a duplicate; I saw that answer but it is 7 years old and involves very complicated answers using pre-ES6 js. I'm suggesting that my question, which allows for ES6, has a dramatically simpler solution.
推荐答案
这很复杂.我做了很多尝试,最后,这种单行代码适用于我的自定义ES6类实例:
It is complicated. I tried a lot, in the end this one-liner worked for my custom ES6 class instances:
let clone = Object.assign( Object.create( Object.getPrototypeOf(orig)), orig)
它避免设置原型,因为他们说会大大降低代码的速度.
It avoids to set the prototype, because they say it slows down the code a lot.
它支持符号,但不适用于getter/setter且不适用于不可枚举的属性(请参见
It supports symbols but isn't perfect for getters/setters and isn't working with non-enumerable properties (see Object.assign() docs). Also, cloning basic internal classes (like Array, Date, RegExp, Map, etc.) sadly often seems to need some individual handling.
结论:这是一团糟.希望,一旦有了本地干净的克隆功能.
Conclusion: It is a mess. Let's hope, once there will be a native and clean clone functionality.
这篇关于如何克隆JavaScript ES6类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!