How do I clone a JavaScript class instance?

后端 未结 6 1989
悲哀的现实
悲哀的现实 2020-11-29 08:50

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

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 08:51

    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:

    1. Create the new object using Object.create from a prototype and a properties object.
    2. For the prototype of the object to be cloned, use the prototype of the original object, using Object.getPrototypeOf.
    3. To create the properties object, loop over the own properties of the original object (using getOwnPropertyNames), and retrieve the property descriptor for each using getOwnPropertyDescriptor.
    4. Apply the extensibility/sealed/frozen characteristics of the original object to the clone.

    This will not deep-clone properties whose values are themselves objects. That's left as an exercise to the reader...YMMV.

提交回复
热议问题