Bracket Syntax Reminder

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:
  1. var s:Sprite = Sprite(addChild(new Sprite()));
  2. s["x"] = 100;
  3. s["y"] = 100;
  4.  
  5. s["graphics"]["beginFill"](0xFF0000);
  6. s["graphics"]["drawCircle"](0,0,10);
  7.  
  8. 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.

This entry was posted in dynamic, functions and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. DieTapete
    Posted March 9, 2010 at 12:25 pm | Permalink

    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. :D

  2. Posted March 9, 2010 at 5:12 pm | Permalink

    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… :D

  3. Posted March 10, 2010 at 4:36 am | Permalink

    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.

  4. Posted March 10, 2010 at 7:55 am | Permalink

    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 :D

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*