-
-
Save GeorgeGkas/36f7a7f9a9641c2115a11d58233ebed2 to your computer and use it in GitHub Desktop.
/** | |
* @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)), | |
); | |
} |
"Uncaught TypeError: clone is not a constructor" - how to deal with it?
@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 ^
thank you, random github people. this saved my day
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
Thanks for this! I've considered a few options and this seems to be the best way to copy a JavaScript class instance.