Specializing in search engine obfuscation

Flash AS3: check if an AS3 method exists

If you build in Flash, you know that each new release of Flash will have new features in Actionscript3. For example, there is a bug in Flash 9 (CS3) with the Loader.unload() method that can cause it to hang on to the loaded item in memory (details here). This was fixed (sort of) in Flash 10 with the Loader.unloadAndStop() method. There are also other features, such as byteArrays that weren’t available in Flash 9, but were added in Flash 10.

At my job, we have created a class package for commonly used functionality, such as asset loading. But what if we want to use a method like Loader.unloadAndStop() in one of these classes? If the project is published in Flash 9, the compiler will throw an error. We could simply use the Loader.unload() method, but we really want to use newer method if the project is published in Flash 10. As always, the Flash community comes to my rescue with this:

var methodExist:Boolean;
try { //FP10 and up:
	methodExist = this["unloadAndStop"] != null;
} 
catch (e:Error) { //FP9:
	methodExist = this["unload"] != null;
} 

This handy little snippet of code will work in any version of AS3. It looks for the newer function and runs it if it exists. If it doesn’t exist, it reverts back to the older code. This is a lifesaver. It allows me to run the “best” version of Actionscript, based on the publish settings of the project.

The original forum thread where I found this solution is here.

Previous

Flash AS3: dynamically draw a mask with lines

Next

Flash AS3: Track SWF memory usage and framerate with SWFProfiler

2 Comments

  1. I go about it differently, so many ways to skin a cat…. here is a method from one of my utility classes:

    public static function functionExists(obj:Object, name:String):Boolean {
    	if ( obj == null ) return false; 
    	if (obj.hasOwnProperty(name)){
    		return true;
    	} else { return false; }
    }
    

    so i do something like: UtilityClass.functionExists( this , ‘unloadAndStop’ );

  2. admin

    @Karim
    Thanks Karim, that’s a great way to abstract the function for general use. My simple code can actually be simplified even more:

    try { //FP10 and up:
        this.unloadAndStop();
    catch { //FP9:
        this.unload();
    }

Powered by WordPress & Theme by Anders Norén