Grant Skinner

The "g" in gskinner. Also the "skinner".

@gskinner

Quick Way to Set Props on a New Instance

I recently posted a feature request for AS3 asking for property initialization for instance construction. If you want details, check out bug #ASL-69.

In one of the comments, I referenced an existing way to quickly set properties on a new typed object, and thought it might be worth sharing. It’s super simple, but might prove useful.

Simply put the following code into a “setProps.as” file in your class path:

package {
public function setProps(o:Object, props:Object):* {
for (var n:String in props) {
o[n] = props[n];
}
return o;
}
}

Now, from anywhere in your code, you can quickly set multiple properties on an object. This can be handy when creating new instances. For example:

addChild( setProps( new Sprite(), {x:200, y:200, alpha:0.5, name:"bob"} ) );

This obviously isn’t type-safe, and it won’t provide compile time errors if you get a property name wrong. For small projects with short timelines, or just playing around it can make it easier to hack things together, but I don’t recommend it for larger or more formal projects.

The goal of my feature request was to enable similar ease of use, but with type safety, compile time errors, and full IDE support. Feel free to vote for it here.