美文网首页
most-elegant-way-to-clone-a-java

most-elegant-way-to-clone-a-java

作者: 司徒雷斯 | 来源:发表于2015-05-08 11:32 被阅读37次

    To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object's prototype that should be left in the prototype and not copied to the new instance. If, for instance, you are adding aclonemethod toObject.prototype, as some answers depict, you will need to explicitly skip that attribute. But what if there are other additional methods added toObject.prototype, or other intermediate prototypes, that you don't know about? In that case, you will copy attributes you shouldn't, so you need to detect unforeseen, non-local attributes with thehasOwnPropertymethod.

    In addition to non-enumerable attributes, you'll encounter a tougher problem when you try to copy objects that have hidden properties. For example,prototypeis a hidden property of a function. Also, an object's prototype is referenced with the attribute__proto__, which is also hidden, and will not be copied by a for/in loop iterating over the source object's attributes. I think__proto__might be specific to Firefox's JavaScript interpreter and it may be something different in other browsers, but you get the picture. Not everything is enumerable. You can copy a hidden attribute if you know its name, but I don't know of any way to discover it automatically.

    Yet another snag in the quest for an elegant solution is the problem of setting up the prototype inheritance correctly. If your source object's prototype isObject, then simply creating a new general object with {} will work, but if the source's prototype is some descendant ofObject, then you are going to be missing the additional members from that prototype which you skipped using thehasOwnPropertyfilter, or which were in the prototype, but weren't enumerable in the first place. One solution might be to call the source object'sconstructorproperty to get the initial copy object and then copy over the attributes, but then you still will not get non-enumerable attributes. For example, aDateobject stores its data as a hidden member:

    functionclone(obj){if(null==obj||"object"!=typeofobj)returnobj;varcopy=obj.constructor();for(varattrinobj){if(obj.hasOwnProperty(attr))copy[attr]=obj[attr];}returncopy;}vard1=newDate();/* Wait for 5 seconds. */varstart=(newDate()).getTime();while((newDate()).getTime()-start<5000);vard2=clone(d1);alert("d1 = "+d1.toString()+"\nd2 = "+d2.toString());

    The date string for d1 will be 5 seconds behind that of d2. A way to make one Date the same as another is by calling thesetTimemethod, but that is specific to the Date class. I don't think there is a bullet-proof general solution to this problem, though I would be happy to be wrong!

    When I had to implement general deep copying I ended up compromising by assuming that I would only need to copy a plainObject,Array,Date,String,Number, orBoolean. The last 3 types are immutable, so I could perform a shallow copy and not worry about it changing. I further assumed that any elements contained in Object or Array would also be one of the 6 simple types in that list. This can be accomplished with code like the following:

    functionclone(obj){varcopy;// Handle the 3 simple types, and null or undefinedif(null==obj||"object"!=typeofobj)returnobj;// Handle Dateif(objinstanceofDate){copy=newDate();copy.setTime(obj.getTime());returncopy;}// Handle Arrayif(objinstanceofArray){copy=[];for(vari=0,len=obj.length;i

    The above function will work adequately for the 6 simple types I mentioned, as long as the data in the objects and arrays form a tree structure. That is, there isn't more than one reference to the same data in the object. For example:

    // This would be cloneable:vartree={"left":{"left":null,"right":null,"data":3},"right":null,"data":8};// This would kind-of work, but you would get 2 copies of the// inner node instead of 2 references to the same copyvardirectedAcylicGraph={"left":{"left":null,"right":null,"data":3},"data":8};directedAcyclicGraph["right"]=directedAcyclicGraph["left"];// Cloning this would cause a stack overflow due to infinite recursion:varcylicGraph={"left":{"left":null,"right":null,"data":3},"data":8};cylicGraph["right"]=cylicGraph;

    It will not be able to handle any JavaScript object, but it may be sufficient for many purposes as long as you don't assume that it will just work for anything you throw at it.

    相关文章

      网友评论

          本文标题:most-elegant-way-to-clone-a-java

          本文链接:https://www.haomeiwen.com/subject/kvuwfttx.html