How to clone a JavaScript class instance?

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

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

How to clone a JavaScript class instance?

To clone a JavaScript class instance, we can use some object methods.

For instance, we write:

class Foo {
  constructor(x) {
    this.x = x
  }
}

const foo = new Foo('bar')
const fooClone = Object.assign(Object.create(Object.getPrototypeOf(foo)), foo)
console.log(foo)
console.log(fooClone)

to create the Foo class.

Then we create a new Foo instance and assign it to foo.

To create a clone of foo, we call Object.create to create a new Foo instance with Object.getPrototypeOf(foo).

Then we call Object.assign to merge the contents of foo into the cloned object.

Conclusion

To clone a JavaScript class instance, we can use some object methods.