I have a need to combine an object with a second object, and if the second object has a property of the first object, the value of the two object will prevail.
Just beginning to feel like this is a very simple function, it's written like this:
/** * Merges the object src into DES, encounters the same attribute as the Des attribute, and notes that the attribute is also deep copy * @param des target Object * @param src object to be merged */function Merge2object (DES,SRC) { if (typeof (DES)! = "Object" | | typeof (SRC)! = "Object") { throw new TypeError (); } For (var prop in Src) { if (Des.hasownproperty (prop)) continue; else Des[prop] = Src[prop]; }}
The result later encountered some errors, after the investigation, found that this function is really a slag: I forgot that if value is another object, the value corresponding to a key of the SRC object will be referenced in the past. This can cause SRC to be modified by some obscure place. So this function needs to be changed:
function Merge2object (des,src) { if (typeof (DES) = "Object" | | typeof (SRC)! = "Object") { throw new TypeError (); } For (var prop in Src) { if (Des.hasownproperty (prop)) continue; else //des[prop] = Src[prop]; Des[prop] = Deepclone (Src[prop]);} }
/*** deep Copy an object * @param obj to deep copy the object */function deepclone (obj) { if (typeof (obj)! = "Object" | | obj = = NULL)//Use = = to cover null and Undefined return obj; When obj is an object, var re_obj = {}; for (var key in obj) { Re_obj[key] = Deepclone (Obj[key]);//Recursion down }return re_obj;}
It seems to be careful to write something later.
An object-merged function throws an error