Please note that ExpatTech no longer operates regular office hours, meeting is by appointment only. Please call +36306031104 for details.

ExpatTech Techblog

Peter Todd 2011.01.17. 11:52

Flash Cookbook - Tricks - Shortening code

This trick is about shortening actionscript code.

Let's have the following lines, written with the original structure:

var movie:MovieClip = new MovieClip();
addChild(movie);
movie.graphics.clear();
movie.graphics.beginFill(0xff0000);
movie.graphics.drawRect(0, 0, 100, 100);
movie.graphics..endFill();
movie.addEventListener("click", mc);

The code above will create a new MovieClip instance, paint it a red rectangle and associate it with a click event. Let's see what happens at each step.

(1) var movie:MovieClip = new MovieClip();
(2) addChild(movie);
movie.graphics.clear();
movie.graphics.beginFill(0xff0000);
movie.graphics.drawRect(0, 0, 100, 100);
movie.graphics.endFill();
movie.addEventListener("click", mc);

We marked the first two lines as these lines hold some good options when it comes to shortening. Note, that this tutorial will show you how to compact your code: it won't do any optimizations concerning speed or performance (at least we haven't measured it), but will compact and only compact your code.

(1) new MovieClip() returns the instance itself, that's why you can assign it to a variable. Basically "var movie:MovieClip" creates the variable, then you assign the return value of operator "new". This is how to imagine it the easiest way.

(2) addChild(instance) also returns the instance.

By understanding (1) and (2) we soon realize we didn't really use these returns in the code. What came after is simply using the variable name and do some functions with the instance.

The lines under (2) can be replaced by with(instance.graphics), that's pretty well used. But let's see now what can we do with the whole expression.

(1) var movie:MovieClip;
(2) with((addChild(movie = new MovieClip())as MovieClip)) graphics.clear(), graphics.beginFill(0xff0000), graphics.drawRect(0, 0, 100, 100), graphics.endFill(), addEventListener("click", mc);

We compacted the whole expression into two lines:
(1) creates the instance
(2) ADDS the child, what is a new MovieClip, to the stage, and WITH its graphics paint it, and assign a listener to it.

This becomes handy if you find it handy.