2011
04.15

This is a quick post to let everyone aware that instanceof should be avoided like the plague in your Flex/ActionScript 3 projects. Coming from a Java development background I was quite familiar with using instanceof to test if a class is of a certain type, in Java this also matches interfaces, not so in ActionScript.

To illustrate the problem, here are some simple classes and an interface:

public class Vehicle {
    private var _name:String;

    public function Vehicle(name:String)
    {
        _name = name;
    }

    public function get name():String
    {
        return _name;
    }

    public function drive():void
    {
        trace("Vehicle named "+_name+" drove.");
    }
}

public interface IManualGears {

    function changeGear(gear:int):void;

}

public class ManualCar extends Vehicle implements IManualGears {

    public function ManualCar(name:String)
    {
        super(name);
    }

    public function changeGear(gear:int):void
    {
        trace("Vehicle named "+_name+" changed gear to "+gear);
    }

}

If I were to create a new instance of ManualCar and tested for the interface IManualGears using instanceof it would fail, as shown below;

var car:ManualCar = new ManualCar("Ford Escort");

var isVehicle:Boolean = (car instanceof Vehicle);  //isVehicle would be true

var isManualCar:Booelan = (car instanceof ManualCar);  //isManualCar would be true

var hasGears:Boolean = (car instanceof IManualGears);  //hasGears would be false

hasGears:Boolean = (car is IManualGears);  //hasGears would be true;

To be fair this is stated in the flex documentation, but it did catch me out. So the moral of the story is to always use is instead of instanceof.

1 comment so far

Add Your Comment
  1. […] See the article here: The Open Coder » instanceof is bad in ActionScript […]