views:

216

answers:

2

how to make a class function with actionscript, I need to have a few static tool functions that are easily used from other classes like test = tools.rtrim(xx);

e.g. this does not compile:

package com.my.tools
{
static function rtrim(string:String):String {
      return string.replace(/\s+$/,"");

     }
}
+6  A: 

It needs to be attached to a class type not a package

Try

package com.my.tools
{
     public class Tools
     {
         public static function rtrim(string:String):String 
         {
                return string.replace(/\s+$/,"");
         }
     }
}

You can then use it through Tools.rtrim("yourString");

James Hay
+4  A: 

In case your collection of tools gets big it may be useful to use top-level functions as well. Specially if you want to reuse a tiny selection of your "tools" in other projects without wasting file size by compiling the unused ones (which happens if you include them all in the same class).

In order to do so, in your package folder you will have to create one file per function. Each file should be named the same way as its related function. e.g. the content of each file named rtrim.as would look like this :

package com.my.tools {

    public function rtrim(str:String) : String {

     return string.replace(/\s+$/,""); 
    }
}

Then you will just have to import the top-level function where you need it :

package my {

    import com.my.tools.rtrim; 

    public class Test 
    {
     rtrim("bla bla");
    }
}
Theo.T