0

any way of doing this is as3?

for example, if I have a var dog:String, how can I get "dog" out of that variable?

Looking into reflection to do this, but there's got to be an easier way

-- A

4
  • 1
    Does this make sense? Because the var name is not important. If it is then you should probably use some kind of object key/value map. Also what do you expect to get if you do var dog:String; var cat:String = dog; Commented Dec 9, 2011 at 0:10
  • 1
    It does.... i'd like to find a way to automatically map XML node values to a VO class's public propeties Commented Dec 9, 2011 at 0:42
  • Seems like you are asking the wrong question. You might have better luck in asking what you want to achieve, rather than asking this kind of question. An example might be "How can you automatically map XML node values to a VO class's public properties?" Commented Dec 9, 2011 at 2:42
  • 1
    now way to do this without reflection. Commented Dec 9, 2011 at 5:02

4 Answers 4

3

Hope this helps.

class A {
   var dog:String = "something";
   var cat:String = "eatdog";
}

function getVars(obj:*):void
{
    for(var i:* in obj){
        trace( i + " : " + obj[i]);
        // this will trace all properties of object.
        // dog : somthing
        // cat : eatdog
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1
  • First of all if it's an instance of a custom class, you can override the toString() method.

  • If it's a property of the class, you can use this method — https://stackoverflow.com/posts/3781635/revisions

  • If it's a local variable, there is no way to get that name.

Comments

1

Sounds like you don't want to "get" the string representation of a variable name, but rather set the variable based on a string.

To set a variable that you have its name as a string you can do this:

this['dog'] = 'value of the dog var';

1 Comment

+1 Just note this won't work unless this is dynamic (or has the property dog).
0

In your example I don't think there is a way to retrieve "dog" as a String.

However, if dog is a property of a dynamic Object, then you could use a function like this:

function getVarName(subject:*, value:*):String
{
    for(var i:String in subject)
    {
        if(subject[i] == value) return i;
    }

    return "";
}

This function can work in a scenario like this:

var holder:Object = {
    dog: "some awesome dog"
}

trace(getVarName(holder, "some awesome dog")); // dog

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.