Posts Tagged ‘constructor’

Switch-case for object’s class type

Friday, August 31st, 2012

Quick tip; instead of using a bunch of “if (x is y) else if (x is z) else” conditionals, you can simply get the class of any object using the “constructor” property. It’s not exposed trough strict typing though, so you have to typecast your instance to Object to access it.

This allows you to have a switch-case for an object’s class:

function addShape(shape:Shape):void {
	switch (Object(shape).constructor) {
		case Circle:
			trace("It's a circle");
			break;
		case Square:
			trace("It's a square");
			break;
		default:
			trace("Unknown shape");
	}
}

Throwing an error in a constructor before the super() statement

Friday, April 13th, 2012

I would have thought you could throw an error whenever you pleased like it, however the Flex compiler has some other ideas.

If you have a throw statement before the super() in the constructor, Flex will complain with the following error code:
1201: A super statement cannot occur after a this, super, return, or throw statement.

There is a workaround though, just wrap the throw statement in an anonymous function:

(function():void {
	throw new Error("Yay for workarounds!");
})();

Populating a Vector in the constructor

Wednesday, January 19th, 2011

There is a small difference between populating a Vector while instancing it and an Array.
While an Array is instanced this way:

var names:Array = ["Bob", "Larry", "Sarah"];

a Vector can be instanced like this:

// In the constructor
var names:Vector.<String> = new <String>["Bob", "Larry", "Sarah"];
// Converting from a regular Array using the Vector global (about three times slower)
var names:Vector.<String> = Vector.<String>(["Bob", "Larry", "Sarah"]);