Article

How to define your own global function in as3

It is very easy. However, I’ve found no info on this topic in the web. I wonder why? First answer: everyone knows how to define the top-level function in AS3 so no-one even drops a line about such obvious thing. Second answer: my search strategy is wrong. Anyway, the approach to your own global functions in Flash9 is really simple, just two steps for those who still miss this feature.

To define your own top-level function (for example, “myTrace“) in AS3:

1. Create the file named “myTrace.as” in the root of your classpath directory.
2. Add the following code and save it:

package {
	public static function myTrace(strToTrace:String)
	{
		trace("myTrace says: " + strToTrace);
	}
}

3. That’s all.
Now your myTrace function is the top-level one. It is visible from ANY of your AS3 classes with NO imports. No hacks. You can call it “global method in AS3″ or “top-level function in AS3″ or whatever you like. This is amazing and I wonder why no one even blogged a line about such simple and great solution except the Miramax at as3.ru. Am I missing something evident here? Feeling like complete n00b.

Comments (3 comments)

[…] e.dolecki wrote an interesting post today!.Here’s a quick excerptIt is very easy. However, I??™ve found no info on this topic in the web. I wonder why? First answer: everyone knows how to define the top-level function in AS3 so no-one even drops a line about such obvious thing. Second answer: my search … […]

GadgetGadget.info - Gadgets on the web » How to define your own global function in as3 / September 29th, 2007, 10:10 pm / #

Wow! I’ve spent a while searching for this too… now i can finally get an important feature in my project done! Thank you!

Datalore / October 13th, 2007, 1:24 am / #

Datalore, I’m glad this helped someone :)

BTW, I’ve found that it is even better to have the top-level class (no package) with short name, and store utility functions there. The benefit is you still need no import the class, but can easily refer to it from anywhere. In my case it is the De.bug and De.log methods I use in my app to track the logs and bugs.

Happy coding :)

Rost / October 13th, 2007, 8:06 pm / #

Post a comment

Best entries: RoR Caingorm Generator, XPath for haXe, haXe FLV, PV3D wiki, Benny the Brave, ++++++ , Flash CS3 Illustrator import, Adobe SOC, JSAPI feature, Apollo 3D Test, Skins for Flex / AIR, DVD Rippers, Name Japaneser, 7+ , White hat SEO for Flash Platform, Google 3D Maps v 0.4, Firefox search plugins, HD TV and MPEG-4 in FP9, Flex VoIP, Kongregate , 8+ , Comments gathering, 3D Alternativa Game, Global function in as3, CS3 Master, Away3D, FB for Linux, DoFollow, 9+ , Bruce Eckel on Flex , Bee desktop blog editor , Saffron UML Tool, Aptana IDE with AIR, Flv Player 2.0, MKSS.EXE troubles, Flickr loves Flash, RIA battles, Top Evangelists, Amazing 3D, 0+ , Alternativa Game in 2008, RAFPUG-2, Flex 3 Skin Issue, IntelliJ IDEA for Flex, Polar Distortion in AS3.