If you haven't looked at every post on this site it's possible you've missed one of my favorite actionscript features.... Bracket Syntax:
Actionscript:
-
var s:Sprite = Sprite(addChild(new Sprite()));
-
s["x"] = 100;
-
s["y"] = 100;
-
-
s["graphics"]["beginFill"](0xFF0000);
-
s["graphics"]["drawCircle"](0,0,10);
-
-
this["addChild"](s);
If you don't realize how powerful this is then there is something wrong with you (joking). If you don't see how powerful this is, take some time and think about it. You can use it to avoid lots of annoying repetitive code in state machines for instance. It's always important to keep things readable if you decide to go this route on a real project.
[EDIT ....and as Quasimondo mentioned there is a notable performance hit when using this syntax. So don't forget to keep that in mind.]
Here is a very old post showing some of the power of this trick.
4 Comments
Yeah, it’s really cool.. But I always feel bad when I do it because I always think every “real” coder would break my neck when he sees it.
If you program to an interface no one should care how the public methods in your class work. If you can create a simple parameterized factory using brackets and an object no one will know unless they look at the code…. So, my advice is use it when it makes sense to. It is part of AS3 after all…
Apart from being horrible to debug the issue with this syntax is that it will run slower than the equal code in non-bracket syntax since the compiler cannot make any optimizations. Especially with the latest Flash player this difference can be quite big. Maybe you have some time to do some speed tests comparing the two.
Good Point Mario. It’s always worth considering the huge performance loss with this. I should have mentioned it in the post maybe.
However, not all apps are in need of super performance… and as a language feature if used properly it can save some time and solve some interesting problems. I used it to write a pretty basic a scheme interpreter so that I could call my functions things like:
this["+"] = function(a:Number, b:Number):Number
I may post a simple speed test… I’m a bit lazy though