How do I clone a JavaScript class instance?
I tried the normal jQuery extend, but that just returns a vanilla object. I have looked through many other answers on sta
You should try something like this:
function clone_object(o){
var n=Object.create(
Object.getPrototypeOf(o),
Object.getOwnPropertyNames(o).reduce(
function(prev,cur){
prev[cur]=Object.getOwnPropertyDescriptor(o,cur);
return prev;
},
{}
)
);
if(!Object.isExtensible(o)){Object.preventExtensions(n);}
if(Object.isSealed(o)){Object.seal(n);}
if(Object.isFrozen(o)){Object.freeze(n);}
return n;
}
Narrative:
Object.create from a prototype and a properties object.Object.getPrototypeOf.getOwnPropertyNames), and retrieve the property descriptor for each using getOwnPropertyDescriptor.This will not deep-clone properties whose values are themselves objects. That's left as an exercise to the reader...YMMV.