Strict Data Typing Variables


Another great feature in ActionScript 2.0 is strict data typing. Strict data typing is the ability to declare the data type of a variable when that variable is initialized. This helps a great deal in debugging large applications. For instance, if you have a login variable that will hold the user's login name as a string, you do not want it accidentally changing to a number or hexadecimal color by accident later in the code.

In ActionScript 1.0, it was possible to have a variable change data types constantly through an application. This is not good coding practice.

This was allowed in ActionScript 1.0:

 var myName = "David";         //declares the variable myName with a String myName = 12;                  //places a number in myName myName = 0xff0000;            //changes myName to a hexadecimal color of red myName=function(){}           //changes myName to a function 

And, truth be told, this is still allowed in ActionScript 2.0, but that is because we have not used the strict data typing features yet.

To use the new strict data typing features when declaring variables, first use the keyword var and then the name of the variable followed by a colon. At this point a pop-up list of all the available data types including component data types appears, as you can see in Figure 8.4.

Figure 8.4. The pop-up list of all available data types in the Actions panel.


You can also see the list of allowable data types by choosing the Add a New Item to the Script button in the Actions panel, and going down to Types.

Here is a correct declaration of a variable in ActionScript 2.0:

   var myName:String = "David";        //declares the myName variable as type String   var myAge:Number = 25;             //declares the myAge variable as type number   var myObject:Object = new Object();     //declares a new object type Object 

Now that these variables are declared, if at any time within the code, we attempt to change the variable's data type, when we either test the movie or check the syntax, we will receive an error.

To see this error, try this code:

 var myName:String = "David"; myName = 25; 

Now test this code, and you should see an error in the Output panel as shown in Figure 8.5.

Figure 8.5. The error seen when a strict data type of a variable is changed.


Strict data typing is not limited to variables, however; they can also be very useful in functions.




Macromedia Flash Professional 8 Unleashed
Macromedia Flash Professional 8 Unleashed
ISBN: 0672327619
EAN: 2147483647
Year: 2005
Pages: 319

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net