如何克隆一个 javascript ES6 类实例 [英] How to clone a javascript ES6 class instance

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

问题描述

如何使用 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 setting the prototype because they say it slows down the code a lot.

它支持符号,但不适合 getter/setter 并且不能处理不可枚举的属性(参见 Object.assign() 文档).此外,可悲的是,克隆基本的内部类(如 Array、Date、RegExp、Map 等)似乎经常需要一些单独的处理.

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 that there will one day be a native and clean clone functionality.

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

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