THE RARELY USED AS3 WITH KEYWORDSep 22, 2008

Recently, I learned about the with keyword in ActionScript 3. I've been programming in AS3 for more than six months by now but I've never seen that keyword used in any source code or book I've read. I saw it for the first time in Colin Mook's Essential ActionScript 3. It can be used to write cleaner code when setting multiple properties of the same object. For example, suppose you want to set some properties in a custom Event class before dispatching it. It may look something like this:

var userEvent : UserEvent = new UserEvent( UserEvent.SET_INFO );
userEvent.age = 20;
userEvent.firstName = "Vladimir";
userEvent.lastName = "Angelov";
userEvent.friendsIds = [4, 3, 23, 6];
userEvent.description = "Some personal desc.";
userEvent.country = "Bulgaria";

dispatchEvent( userEvent );

By using with it will look like that:

var userEvent : UserEvent = new UserEvent( UserEvent.SET_INFO );
with( userEvent ) {
age = 20;
firstName = "Vladimir";
lastName = "Angelov";
friendsIds = [4, 3, 23, 6];
description = "Some personal desc.";
country = "Bulgaria";
}

dispatchEvent( userEvent );

The second example is somehow cleaner and you don't need to type the name of the object everytime you set some of its properties. Of course it's not worth using it you are only setting few variables.

posted by
Fri, 07/03/2009 - 1:19pm

I wanted to say how amazing the "with" keywork is. It's available in tons of OOP languages and saves so much time and energy.


posted by
Thu, 10/08/2009 - 4:39am

Thanks for posting!


posted by
Sun, 01/24/2010 - 6:03pm

A warning about using the "with" keyword: Any assignments, class references, values, etc that used within a "with" block are NOT evaluated at compile time.

This means that any errors from: referencing a non-existent property on the "with" object, invalid class references, and any other errors/warnings that would normally be received compile-time --- they are ONLY thrown during execution of the block during run-time.

While this isn't necessarily a game-stopper, it's valuable information to know. When I only have a few properties to set, I avoid using the with keyboard at the expense of some slight redundancy.

Cheers!



Post A Comment

To post comments, please log in or register.

Textback theme designed by Amy & Pink