1

I'm trying to turn an string into an instance name.

stage.focus = ["box_"+[i+1]];

this gives me back = box_2;

but I need it to be an object not a string.

In as2 I could use eval. How do I do it in as3?

3 Answers 3

9

The correct syntax is:

this["box_"+(i+1)]
Sign up to request clarification or add additional context in comments.

2 Comments

+1 in my answer I was adding . after this, and deleting my answer.
Thanks, Dani! that if fact is the correct syntax! stage.focus = this["box_"+(i+1)];
2

For example if you would like to call the function "start" in your main class, you'd do it this way:

this["start"]();

Same thing goes for variables. Since all classes are a subclass of Object you can retrieve their variables like you would with an ordinary object. A class like this:

package{
    import flash.display.Sprite;
    public class Main extends Sprite{
        public var button:Sprite;

        public function Main(){
            trace(this["button"]);
        }
    }
}

Would output:

[object Sprite]

Comments

0

If you want to access a member of the current class, the answers already given will work. But if the instance you are looking isn't part of the class, you are out of luck.

For example:

private function foo():void {
    var box_2:Sprite;
    trace(this["box_"+(i+1)]);
}

Won't work, because box_2 isn't a part of the class. In that case, it is highly recommended to use an array.

If you want to access a DisplayObject (for example, a Sprite or a MovieClip) you also can use getChildByName. But in that case, box_2 will be the name of the object, instead of the name of the variable. You set the name like

var box:Sprite;
box.name = "box_2";

But again, I recommend an array.

1 Comment

I do have an array, what I wanted was, that after you typed on box_1, if it was correct, to change the focus to box_2...

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.