Quantcast
Channel: VBForums
Viewing all articles
Browse latest Browse all 15067

Cloning Objects: Merging and Matching of objects

$
0
0
Creating a new object that merges or copies other objects can create "referential" links that can burn you later on. You can easily have two objects with members that actually refer to the same address in memory. Changing one will change the other! This can cause major bugs if you are not expecting this!

I use these functions mostly when dealing with AJAX calls and "call back" functions that fire when web responses come through. I also use them when "cloning" objects to make "new" objects (ones that might be "saving" filter settings that users can maintain and copy and what not).

Function #1: mergeObjects()

This function will merge two objects. If the "property" already exists it WILL NOT be touched. Any new properties in objFiller will be created in objMaster.

This function copies the "value" of the element, so it should only be used for objects that have "value" type properties only.

If you are merging objects that have properties that are arrays or objects themselves, use the next function (mergeObjectsDeep)

Code:

function mergeObjects(objMaster, objFiller) {
    for (var propertyName in objFiller) {
        if (typeof objMaster[propertyName] == "undefined") {
            objMaster[propertyName] = objFiller[propertyName];
        }
    }
}


Viewing all articles
Browse latest Browse all 15067

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>