SoFunction
Updated on 2025-04-14

Package (package) application instance code in AS3

The concept of package already exists in AS2. It represents a directory structure in the hard disk, which is used to classify and store various types of files. In AS3, this concept can still be understood as a path or directory structure, and the name of the package is the directory location where your class is located.

If the class file and the fla file are saved in the same directory location, then there is no need to specify a name for the "package". For example: Let’s first create such a class definition file, and enter the following code into the file:

package {
    public class MyMsg {
         public function showMsg () {
               trace ( "I'm in the same place with fla file.");
         }
     }
}


Then create an instance of this object in the main scene and call its method program showMsg.

var msg:MyMsg = new MyMsg();
();

Save the fla file and the class file together. After running, you can see that the content we set will be output in the output window.

In the file storage location, we create a directory called dzxz, and create another directory called as3 in it. Create a new class file in the dzxz\as3 directory. It is located in a directory structure, so we need to specify its package name, and the class code is written in the following form:

package dzxz.as3 {
    public class MyMsg2 {
         public function showMsg () {
               trace ( "I'm in the package of dzxz.as3 !");
         }
     }
}

In the main scenario, if you want to use the MyMsg2 class in the package, you must first import the package, use the import statement, add a line of import statement, and change the code to:

import dzxz.as3.MyMsg2;

var msg:MyMsg2 = new MyMsg2();
 ();

(During the test, it was found that if the class name in the package and the class name in the current directory are the same, the current class file will be used first, so the class name in the package will be changed to MyMsg2)

From the previous example, we can find that the package name is written between package and {, and the name of the class file is consistent with the class name MyMsg in it. If the package name is used, the directory structure must be used to store the class files. The advantage of this is that it is not easy to get confused when there are many classes.