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)), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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