AS3 string to function referenced in a class


Many of you may know that in Actionscript 3 you can turn a string into a function simply by doing this


this['my_string_that_is_a_function'];

 


Fairly simple and very useful. However what may not be so obvious is how to reference public functions within other classes. 

Say you have the following class:


package {
    import flash.display.*;
    public class PageBuild extends Sprite {
        public function PageBuild() { }
        public function subView(){
                     trace('hello world');
                }
       }
}

 


Within another part of your project you have called that class in and now want to access the public function 'subView' but the reference to that function is in a string attached to a MouseEvent. 

Something like this,


private function subMenuClick(evt:MouseEvent):void
{
        // call our PageBuild class
    var subPageLoad:PageBuild = new PageBuild();
    contentClip.addChild(subPageLoad);
}

 



At first I thought I could use this[] however that obviously won't work as 'this' does mean 'this', easy to forget on this topic as most of the online examples point to just use this['string']. Anyway as we know this == this then logically all we do if we want to call a function within our PageBuild class is this



subPageLoad[evt.currentTarget.stringFunction]()


Just to make this clear. 'subPageLoad' is the name of the instance of our PageBuild class, so works like this in this context. Right I have said this too much now. 

FINAL CODE


private function subMenuClick(evt:MouseEvent):void
{            
    var subPageLoad:PageBuild = new PageBuild();
    contentClip.addChild(subPageLoad);
             
    subPageLoad[evt.currentTarget.stringFunction]();
}



I hope that helps anyone who needs to turn a string to a function.