Simple single line initialization of objects

One thing I really miss about AS2 was the simple single line initialization of new MovieClips. It was great to set the x, y, width and height properties when the MovieClip was added.

So what I have done in new Classes I create is add a little helper method that allows me to add all the properties on initialization.

The snippet is as follows:

protected function initProps($props):void
{
    for (var prop:* in $props) {
        try { this[prop] = $props[prop]; }
        catch(e:ReferenceError)  { trace(prop + " is a property that doesn't exist"); }
    }
}

In the constructor add $props:Object = null as an argument and call the initProps method if he object exists, like this.

public function Box($props:Object = null)
{
       // constructor

       if($props) initProps($props);
}

Or alternatively, you can create a utility method that will work on ANY object.

public static function initProps($obj:*, $props:Object):*
		{
			for (var prop:* in $props) {
				try { $obj[prop] = $props[prop]; }
				catch(e:ReferenceError)  { trace(prop + " is a property that doesn't exist on "+$obj); }
			}

			return $obj;
		}

How it works

What happens in the initProps method, is we loop through the $props object, apply the property name to the object and then add the value. Simple.

If the property doesn’t exist on this object, it will trace out a the line “(the unknown property) is a property that doesn’t exist”.

Now when you want to create a new Box object you can initialize it with all the properties in one line.


var box:Box = new Box({ x: 20, y: 40, width: 200, height: 200 });
addChild(box);

Hope this helps you as much as it’s helped me.

This entry was posted in AS3, Flash. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>