Categories
JavaScript Answers

How to clone a JavaScript class instance?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *