Search code examples
javascriptnode.jsecmascript-6es6-class

How to clone a javascript ES6 class instance


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.


Solution

  • 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.