Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  152] [ 4]  / answers: 1 / hits: 81377  / 8 Years ago, wed, january 4, 2017, 12:00:00

How do I clone a Javascript class instance using ES6.



I'm not interested in solutions based on jquery or $extend.



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.



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.


More From » node.js

 Answers
17

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.


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.


[#59458] Monday, January 2, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;