Posts Tagged ‘object’

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");
	}
}