Deep clone class instance JavaScript

typescript clone class instance
javascript clone class instance
javascript deep copy
javascript copy object
javascript class copy constructor
javascript clone static class
object.assign deep copy
javascript clone string

I'm trying to figure out a way to deep clone a JS class instance while preserving all the prototypes down the chain.

I've seen how to deep clone and object:

JSON.parse(JSON.stringify(instance))

And I have seen how to make a shallow copy of a class instance:

Object.assign( Object.create( Object.getPrototypeOf(instance) ), instance)

But my question is, is there a way to deep clone an instance of a class?

There is no foolproof way to clone all possible types of objects in JS, particularly if it contains references to other objects. A generic cloning argument doesn't know whether an object reference in the clone should contain the same reference (such as a common parent) or whether it needs to clone the object i has a reference too also. It isn't possible to know that generically as it really depends upon the implementation of the object.

If there are circular references to objects such as parent to child and child to parent, it gets even more complicated.

As another example, imagine an object that as part of its constructor, it creates a unique object ID, registers that id with some service and then stores the ID in its instance data. There's no way way for a generic clone mechanism to know that logic (generating a new ID and registering it with some service) is required to make a new object. That type of logic would have to be done by code specific to that object that knows what to do.

As another example, a constructor might create closures (with access to private information) that there is no way to duplicate from the outside.

As another example, a constructor might bind methods to its own instance that a generic clone would have no idea it needed to do.

The best way to clone an object is with code built into the implementation of the object that knows how to clone itself such as adding a .clone() method (or name it whatever you want) on the object itself and have the object support making a duplicate of itself. Then, it can do the right thing with any instance data which only the object implementation itself can know how to handle all possible types of instance data.

How to clone class instance in JavaScript, Here's how it works: Object. create() creates a new object and Object. getPrototypeOf() gets the prototype chain of the original instance and adds them to the newly created object. Object. assign() does as we've seen earlier, which is to (shallow) copy the instance variables over to the newly created object. To do a deep copy (vis-a-vis shallow copy), it’s best to use an external library like jQuery or Lodash: // jQuery method var newObject = jQuery.extend(true, {}, oldObject); // lodash method var deep = _.cloneDeep(objects); More details on deep cloning can be found in this SO thread.

I recommend using Lodash's cloneDeep. It works with all types, function and Symbol are copied by reference.

Using the JSON.parse(JSON.stringify(myObject)) way is problematic when there's circular reference. Also, it replaces the object's methods to undefined and reorders the properties.

Deep copy/clone a class instance in Javascript � GitHub, /** * @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( So-called copy constructors, constructors that receive another instance of the current class and use it to initialize the current instance. 14.1 .clone() methods. This technique introduces one method .clone() per class whose instances are to be copied. It returns a deep copy of this. The following example shows three classes that can be cloned.

A possible hack is to invoke the structured clone algorithm to make the clone by sending the instance through a MessageChannel, like this:

function deepClone(instance) {
    return new Promise(resolve => {
        const messageChannel = new MessageChannel();
        messageChannel.port2.onmessage = e => resolve(e.data);
        messageChannel.port1.postMessage(instance);
    });
}

This will handle types like Map, Set, Date, RegExp, Blob, ArrayBuffer and more, and it can even clone custom classes.

Some other ways to trigger a structued clone can be found here.

How to deep clone a JavaScript object, JavaScript offers many ways to copy an object, but not all provide deep copy. Learn the most efficient way, and also find out all the options you� How do I deep clone an object of a user-defined class and also keep the object methods of the class? For example, I have a Object class called Schedule with member days: number[] and function

Clone ES6 class instance, <code>. 7. var original = new SomeClass(/**/);. 8. var clone = Object.assign( Object.create(original), original);. 9. </code>. 10. </pre>. 11. . 12. <h2>Tests</ h2>. const clone = Object.assign( {}, instanceOfBlah ); Object.setPrototypeOf( clone, Blah.prototype ); Note the characteristics of Object.assign: it does a shallow copy and does not copy class methods. If you want a deep copy or more control over the copy then there are the lodash clone functions.

3 Ways to clone objects in JavaScript | by Farzad YZ, Cloning an object in JavaScript a task that is almost always used in any project, to clone everything from simple objects to the most complicated� Summary: My Java deep clone example. As shown, this serialization technique/hack lets you easily make a deep clone of a Java object. As far as I know, the only drawback to this technique is that it requires you to have your classes implement the Java Serializable interface, which is considered a “marker” interface, because it does not define any methods.

How to Deep Copy Objects and Arrays in JavaScript, The usual methods of copying an object or array only make a shallow copy, so deeply-nested references are a problem. You need a deep copy� Note that if you use Nested MemberwiseClone for a deep copy, you have to manually implement a ShallowCopy for each nested level in the class, and a DeepCopy which calls all said ShallowCopy methods to create a complete clone. This is simple: only a few lines in total, see the demo code below.

Comments
  • Are you trying to clone a class itself or an instance of a class? If you're trying to clone a class, please explain why and you can probably just subclass it.
  • I'm trying to clone an instance, I'll edit my question to make it clear
  • There is no foolproof way to clone all possible types of objects in JS, particularly if it contains references to other objects. The best way is to support a .clone() method (or name it whatever you want) on the object itself and have the object support making a duplicate of itself. Then, it can do the right thing with any instance data which only the object implementation itself can know how to handle all possible types of instance data.
  • You shouldn't rely on JSON.parse and stringify to clone objects that are not simple data structures (even then, it's slow). The JSON process computes a one-time value for getters instead of cloning the definition, ignores non-enumerable properties and symbols, prototypes (as you've noticed), and makes no effort at all to handle circular references. That can be improved with the optional argument to JSON.parse and the corresponding one on JSON.stringify.
  • Similar to the registration example, a constructor might create closures or bound methods, and there's no way to access/copy their state from the outside.
  • @Bergi - I added those examples.
  • this should be the answer here, no need to reinvent the wheel, just use Lodash's cloneDeep, works like a charm. And background is quite simple, for a real new Object you need to loop through all keys of an object copy it to the new and also copy the values, if you don't want to miss something
  • I like the idea of using structured clone. A less hacky and actually fast solution would be to just implement it. It's well enough specified that it shouldn't be much trouble.
  • @Touffy do you know of any JavaScript implementations? This sounds like a good idea