Created
July 29, 2018 09:43
-
-
Save GeorgeGkas/36f7a7f9a9641c2115a11d58233ebed2 to your computer and use it in GitHub Desktop.
Deep copy/clone a class instance in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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)), | |
); | |
} |
@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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"Uncaught TypeError: clone is not a constructor" - how to deal with it?