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;

This is equivalent to the version requiring more typing:

someClip.alpha = 0.5;
someClip.scaleX = 2;
someClip.scaleY = 3;

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.