AS3 Dynamic variable naming

404 Views Asked by At

Is dynamic variable naming like this possible in ActionScript 3?

for (var xz=0;xz<10;xz++){
    var this['name' + xz]:Number = xz;
}
3

There are 3 best solutions below

7
On BEST ANSWER

You should use an array for this kind of list of variables. While you can create properties dynamically, you usually want to avoid it. Especially in your case, where the actual identifier of each variable is not a String, but a number. So why not use something that does exactly that: identify its elements by a number? And that's exactly what an array does.

code example:

var xzs:Array = [];
for (var xz:uint = 0; xz < 10; xz++){
    xzs.push(xz);
}
4
On

Yes, it sure is - AS3 comes from ECMA script, so this is setting a property to an object (in this case it's this). So you can dynamically set properties. But you are a little bit wrong about how to do it - there is no need to use var, because you don't declare it, you set it. It's like using:

this.propertyName = 'value';

From now on, this will have propertyName equal to 'value'. Therefore you should just use:

this['name' + xz] = xz;

That's all!

Edit: as BotMaster mentioned - if you are using classes and you want to dynamically add properties, the class must be set as dynamic. Most of the commonly used ones are already dynamic (as Aaron mentioned :)). I didn't go into much details as I think you simply need to do this on your timeline. If not - please specify this in your question so that you can get more accurate answer than this one. The same goes if your new property needs to be typed (can't think of any point wanting this) - you should see BotMaster's answer :)

0
On

Short answer is: no, you can't declare at runtime typed properties.

Long answer is: kinda.

If you want to create new typed properties you'll have to store them in a Vector<>.

Anything else would let you do it but untyped, dynamic class, store in object, store in array, etc ...