How to clone a JavaScript ES6 class instance?

Sometimes, we want to clone a JavaScript ES6 class instance.

In this article, we’ll look at how to clone a JavaScript ES6 class instance.

How to clone a JavaScript ES6 class instance?

To clone a JavaScript ES6 class instance, we can use the Object.assign, Object.create, and Object.getPrototypeOf methods.

For instance, we write:

class Foo {}

const orig = new Foo()
const clone = Object.assign(Object.create(Object.getPrototypeOf(orig)), orig)
console.log(clone)

We create a Foo class with class Foo {}.

Then we create an instance of that with new and assign it to orig.

Next, we call Object.prototypeOf with orig to get the prototype of orig.

And we call Object.create with that to create a new object with the same prototype as orig.

And then we merge that with the orig object itself with Object.assign and assign the returned object to clone.

Therefore, clone is also an instance of Foo and inherits from the same prototype.

Conclusion

To clone a JavaScript ES6 class instance, we can use the Object.assign, Object.create, and Object.getPrototypeOf methods.