Gotcha with ActionScript ‘const’

ActionScript (like JavaScript) lets you access object properties using two different notations. Consider the following class

class A
     public const CONSTANT:int = 34;
var a:A = new A();


The CONSTANT property of object a can be referred using the following two formats:

  • a["CONSTANT"]

Since CONSTANT is declared using const, it cannot be assigned a new value later on. So the following code doesn’t compile (as expected):

a.CONSTANT = 23;


However, the following code compiles and only throws an exception at run-time:

a["CONSTANT"] = 23;


Beware of this behavior of ActionScript when using consts in your code!

One thought on “Gotcha with ActionScript ‘const’

  1. Makes sense; the compiler can’t feasibly validate string types at compile-time (in this case it’s trivial, but what if the string “CONSTANT” is the return of a function, or from a web-service?).

    Just another reason you should never use strings for program logic, in any language.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s