
Code shortening can make your code more readable as well as more unreadable
. While it is recommend to use coding conventions and standards, in some cases you can spare a lot of lines using some shortening. In fact there must not be a conflict between using convetion vs. using shortening, and soon after you get used to some “shortcuts”, your code may be reduced in reasonable amount of lines. Some reading about code optimization can be found here, this article extends optimizations.
Establishes a default object to be used for the execution of a statement or statements, potentially reducing the amount of code that needs to be written. You can use multiple with() statemens:
with(new Date)
with(Math)
trace(hours, sin(0));
List style dynamic switch
Sometimes when you need to “switch” simple input value into output value, all you need is to choose item from list.
var m:uint = 3;
trace(['','I','II','III','IV'][m]);
trace({a:'AA',b:'BB'}['b']);
New instantion / addChild combo
While DisplayObjectContainer.addChild(child) returns inserted child as DisplayObject, you can cast it.
var s:Sprite = Sprite(addChild(new Sprite()))
Anonymous functions
ActionScript lets you put function definition directly where you normally put reference.
addEventListener(Event.ENTER_FRAME, function(event:Event):void
{
trace("anonymous enter frame")
});
In order to get a reference to the currently executing function use arguments.callee. If you need to removeEventListener, use reference not direct definition.
Omitting curly braces
It is possible to omit curly braces with some block statements (for, for each, if, while) on single statement
for(var i:uint=0;i<100;i++)
trace(i)
Joining multiple statements into single-like
In order to create single statement from multiple statement (to omit curly braces) join statements with “,”.
var i:uint;
while(i<10)
i++,trace(i);
Pretty common, but worth mentioning
for(var i:uint = 0; i < 3; i++)
trace(i == 1 ? "BOMB" : i);
Operators (pre-increment, post-increment…)
Also pretty common
var i:uint = 0;
trace(i++, ++i, i--, --i);
i += 1, i *= 2, i /= 2, i -= 1, i %= 2;
The Modulus operator(%) computes the remainder of division between 2 integers. Can be use for alternation (color etc.)
for(var i:uint = 0; i < 10; i++)
trace(i%3 ? i : "BOMB");
Action assignment
Result of assignment is value itself.
var i:uint, j:uint = 0;
trace(i = j = 2);
for statement definition says:
for ([init]; [condition]; [next])
… it means you can use it very creative way
var i:uint = 0;
with(graphics)
for(clear(),lineStyle(1,0);i<10;x=y=100,i++)
lineTo(x*i, y*i*i);
Result of statement using logical OR is the first valid element. It can substitute ternar operator in some cases
trace(null || 0 || "" || "BOMB" || "never");
trace(defined ? defined : "default") // equals to trace(defined || "default")
Class Instantiating without “new”
Most common used is string delimiter (“), but there are also ones for XML and RegExp
var x:XML = <data></data>;
var r:RegExp = /.*/i;
Other