In Action Script 3 most classes are sealed. This means that for most Objects we are not able to create new properties run time beyond those that where available compile time. This is not the case with Array and Object though which are both dynamic and regularly come in handy to us for example in the creation of an associative array (or sometimes called a ‘hash’) :
1 2 3 |
But what to do if you’re in need of creating properties upon an instance that belongs to a sealed class. For example say that we with flash.display.SimpleButton would like to add the property counter which tells us how what time interval to start a timer with. We could not:
1 2 3 | (//import flash.display.SimpleButton etc...) var myBtn:Simple Button = new SimpleButton(); myBtn.timestamp = 1000; |
The above would throw an error as SimpleButton like most classes in ActionScript 3 are sealed. The solution would be to extend SimpleButton with a dynamic class like so :
1 2 3 4 5 6 7 8 9 10 11 | package { import flash.display.SimpleButton; public dynamic class DynamicButton extends SimpleButton { public function DynamicButton() { } } } |
Making use of our dynamic button we could now :
1 2 3 | var dynBtn:DynamicButton = new DynamicButton(); dynBtn.timestamp = 1000; trace ("dynamic button timestamp value " + dynBtn.timestamp); |
And this would compile without errors and work nicely. However there is an other approach to this which comes very handy as a way of creating dynamic properties and referring to them. Here enters the Dictionary Object. This object is a bit like our associative array above but with the big difference that it can take an object itself as lookup key to find a value. For our oranges we get:
1 2 3 4 | var dict:Dictionary = new Dictionary(); var myOrange:Object = new Object(); dict[myOrange] = 101; trace ("number of oranges dictionary approach " + dict[myOrange]); |
Using a Dictionary Object we thus have a way to lookup properties using the objects themselwes rather than using the variable names to refer to properties. This also works for instances of sealed classes such as our button example. We can write:
1 2 3 4 | dict = new Dictionary(); var myButton: SimpleButton = new SimpleButton (); dict[myButton] = 1001; trace ("dictionary button counter value " + dict[myButton]); |
Since the button is the key, it does not matter that SimpleButton is a sealed class. We are not trying to assign a new property to the SimpleButton instance by using a variable name. Instead we use the instance itself and thus we here have a handy way of assigning values also to instances that don’t take new dynamic properties.
Some further readings:
http://www.gskinner.com/blog/archives/2006/07/as3_dictionary.html
http://www.zombieflambe.com/actionscript-3/as3-dictionary-class-array-object-benchmark/
http://pixelwelders.com/blog/best-practices/2008/speed-tests-objects-vs-arrays-vs-dictionaries/