Home » Nodejs » How to clone a javascript ES6 class instance [duplicate]

How to clone a javascript ES6 class instance [duplicate]

Posted by: admin November 30, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:
let clone = Object.assign( Object.create( Object.getPrototypeOf(orig)), orig)

I tried a lot, in the end this worked for me.

It also avoids to set the prototype, because they say it slows down the code a lot.

And it’s a one-liner!

Questions:
Answers:
const clone = Object.assign( {}, instanceOfBlah );
Object.setPrototypeOf( clone, Blah.prototype );

Note the characteristics of Object.assign: it does a shallow copy and does not copy class methods.

If you want a deep copy or more control over the copy then there are the lodash clone functions.