views:

39

answers:

1

i'm attempting to cast an object's property as an actual property of another object.

here's my object variable:

var propObj:Object = {prop:"width", width:50};

now i want to assign the property of a sprite using that object's properties.

var sp:Sprite = new Sprite();
sp.(propObj.prop as Sprite.property) = propObj.width;

now, i'm not even going to try that because i know the compiler will explode all up in my face. but you should be able to see what i'm trying to do.

why i'm trying to do it is because i'm reading in an XML file with an undetermined list of usable properties for specific objects. so instead of writing something like a huge switch statement to evaluate whether the XML file has a value for that specific property, i'm trying to assign properties dynamically based on what's available in the XML file.

if what i'm trying to do is possible, what's the best way to do it?

+2  A: 

With propObj defined as you did, you could do something like:

var propObj:Object = {prop:"x", x:50};
var sp:Sprite = new Sprite();
sp[propObj.prop] = propObj.x;

Now, a more generic and perhaps more useful way of doing what you are trying to do would be:

var props:Object = {x:10,y:50,unexistentProp:300};
for (var propName:String in props) {
    if(sp.hasOwnProperty(propName)) {
        sp[propName] = props[propName];
    }
}

The above code ignores properties that are not defined for the target object. This is necessary for non-dynamic classes like Sprite. Otherwise, your code will throw an Error. It's up to you if you want to do anything about invalid property names; if so, you could add the necessary code in an else. You could also detect an Error with a try/catch, but make sure to catch only this specific expection - ReferenceError -, or this could mask other errors, like null references, etc. Other option would be not checking for errors or try/catching and let the code throw an Error up the call stack. This seems like a bad idea to me, though. It's better to deal with the error as soon as possible (and close as possible to the place it happened).

Juan Pablo Califano
amazing. hadOwnProperty is like a light at the end of the tunnel! why haven't i read about it before?! it's going to make life so much easier. thanks a million!
TheDarkInI1978