Skip to content

Instantly share code, notes, and snippets.

@GeorgeGkas
Created July 29, 2018 09:43
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save GeorgeGkas/36f7a7f9a9641c2115a11d58233ebed2 to your computer and use it in GitHub Desktop.
Save GeorgeGkas/36f7a7f9a9641c2115a11d58233ebed2 to your computer and use it in GitHub Desktop.
Deep copy/clone a class instance in Javascript
/**
* @function
* @description Deep clone a class instance.
* @param {object} instance The class instance you want to clone.
* @returns {object} A new cloned instance.
*/
function clone(instance) {
return Object.assign(
Object.create(
// Set the prototype of the new object to the prototype of the instance.
// Used to allow new object behave like class instance.
Object.getPrototypeOf(instance),
),
// Prevent shallow copies of nested structures like arrays, etc
JSON.parse(JSON.stringify(instance)),
);
}
@cor
Copy link

cor commented May 25, 2020

Thanks for this! I've considered a few options and this seems to be the best way to copy a JavaScript class instance.

@Xsaven
Copy link

Xsaven commented Jun 23, 2020

"Uncaught TypeError: clone is not a constructor" - how to deal with it?

@its4l3x
Copy link

its4l3x commented Feb 9, 2021

@Xsaven it's a function not a class.

Be Sure to Import the Method

then call it like that:

clone(yourInstance)

optional (but my preference):

you can put this function into a class and call it then as function from the instance you've got alrdy (But you have to adjust the syntax to class functions), like

const clonedClass = yourClass.clone(yourInstance)

^ for example ^

@plepisnew
Copy link

thank you, random github people. this saved my day

@Venon282
Copy link

Venon282 commented Jun 7, 2023

I get this error :
Uncaught TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property 'links' -> object with constructor 'Object' | index 0 -> object with constructor 'Object' --- property 'to' closes the circle

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment