With Blocks
While plainly documented by Adobe in the Flash 10 AS3 Docs, it seems as though few programmers know about the with statement. I don’t use them much personally, but when a coworker came across one in my code recently and was puzzled, I figured I would write a quick article to cover their usage.
With blocks are easy to use. They simply change the context to another object. Adobe’s docs are actually out of date and feature AS2 code. Here’s a more modern version for dealing with some MovieClip:
with (someClip) { alpha = 0.5; scaleX = 2; scaleY = 3; gotoAndPlay(1); }
This is equivalent to the version requiring more typing:
someClip.alpha = 0.5; someClip.scaleX = 2; someClip.scaleY = 3; someClip.gotoAndPlay(1);
Keep in mind that this will still refer to the instance of your class if you use it in a non-static method. Other than that, Adobe lists the rules for resolution within a with block:
- The object specified in the object parameter in the innermost with statement
- The object specified in the object parameter in the outermost with statement
- The Activation object (a temporary object that is automatically created when the script calls a function that holds the local variables called in the function)
- The object that contains the currently executing script
- The Global object (built-in objects such as Math and String)
I’m sure everyone reading this article can think of one area of their code where they set a whole lot of fields of one object in a big, long sequence. Why not revisit that area and convert the code to use a with block as an exercise? You could even do this in any AS2 or JavaScript code you have. Go on, give it a try and see if you like it.
#1 by Jonnie on September 16th, 2009 ·
I used to use With blocks when drawing graphics, but pinpointed them as the source of a major memory sponge. The profiler said my graphics class had thousands of instances within seconds, when there were only a dozen constructed. I replaced the With block with everything typed out and that fixed the issue. I just accepted it and moved on, but it still puzzles me.
#2 by jackson on September 16th, 2009 ·
Wow, that is surprising. It seems like such an innocent feature that it would be hard to make a memory leak out of it. Thanks for this tip, I’ll have to look into it further.
#3 by Jonnie on September 26th, 2009 ·
I’m not sure if you caught Grant Skinner’s slides on performance, but his tests show that using var $graphics:Graphics = object.graphics is 10x faster than “with” blocks. http://gskinner.com/talks/quick/#58
#4 by jackson on September 26th, 2009 ·
I did see that and it is distressing! Perhaps it’s a good thing nobody ever uses them. :)