An object-merged function throws an error

Source: Internet
Author: User
Tags hasownproperty

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.