Sunday, February 10, 2013

POD Cloner iterates through non-dynamic properties just fine

package JM_LIB.utils 
{
    import mx.utils.ObjectUtil;
    /**
     * Clones any POD (plain old data) class:
     * @author JMIM
     */
    public class PODClonerUtil 
    {
        
        public function PODClonerUtil() { };
        
        public static function clone(inObj:Object):*
        {
            
            //Step1: Get class of inObj, and instantiate a new object of that type.
            var c:Class = inObj.constructor;
            var newObj:Object = new c(); //POD clases take zero parameters.
            
            //Use Flex's ObjectUtil to extract properties of object.
            var classInfo:Object = ObjectUtil.getClassInfo( c );
            var propArr:Array = classInfo.properties as Array;
            var prop:String;

            //must use this type of loop. Because the other will NOT work.
            for each (prop in propArr)
            {
                if (prop == "prototype") { continue;}
                newObj[ prop ] = inObj[ prop ];
            }
            
            /*
             * //Does same thing as for each loop above.
            for (var i:int = 0; i < propArr.length; i++)
            {
                prop = propArr[i].localName;
                if (prop == "prototype") { continue;}
                newObj[ prop ] = inObj[ prop ];
            }
            */
            
            return newObj;
        }
    }
}

No comments:

Post a Comment