AS3 “with” keyword and casting
I’ve rarely (if ever) used the “with” keyword in as3, but I recently found a neat trick to use it with.
When I quickly need to cast an object to access a few methods/properties I don’t always want to
create a new casted variable:
var child:DisplayObject = getChildThatMightBeMovieClip(); if (child is MovieClip) { var childAsMc:MovieClip = child as MovieClip; trace(childAsMc.numChildren); trace(childAsMc.currentFrame); }
or cast it every single time:
var child:DisplayObject = getChildThatMightBeMovieClip(); if (child is MovieClip) { trace((child as MovieClip).numChildren); trace((child as MovieClip).currentFrame); }
Using the “with” keyword, we can temporarily cast it without creating a temporary casted variable or casting it again and again:
var child:DisplayObject = getChildThatMightBeMovieClip(); if (child is MovieClip) { with (child as MovieClip) { trace(numChildren); trace(currentFrame); } }
Elegant =)
December 16th, 2011 at 08:51
Simpler:
var child:MovieClip = getChildThatMightBeMovieClip() as MovieClip;
if (child) {
…
}
March 3rd, 2012 at 05:08
Thanks
I usually use nested “with”, for my object arrays.
March 8th, 2012 at 17:51
Thanks for the post.
@jooj
checking if (child) wont guarantee whether its a a movie clip or not.
and hence
var child:DisplayObject = getChildThatMightBeMovieClip();
if (child is MovieClip) {
with (child as MovieClip) {
trace(numChildren);
trace(currentFrame);
}
}
stands out….
May 29th, 2012 at 01:53
thank you for sharing.
July 19th, 2012 at 10:43
its good
July 1st, 2013 at 19:37
Question: Does this improve speed of execution over casting over and over, and does this improve memory usage over creating a temporary variable?
August 4th, 2013 at 09:59
This is very likely slower, and I actually recommend using the “as” keyword instead if you want a more proper way of checking this since it’s faster, has compile-time checking of properties and it returns null if the child isn’t moveclip:
The use case that I posted might not be the best way of handling it, I only posted it as an example =)