![]() ![]() ![]() | |
![]() | |
![]() | |
![]() |
ActionScript 2.0 lets you explicitly declare the object type of a variable when you create it; this is called strict data typing. Because data type mismatches trigger compiler errors, strict data typing helps prevent you from assigning the wrong type of data to an existing variable. To assign a specific data type to an item, specify its type using the var
keyword and post-colon syntax:
// strict typing of variable or object var x:Number = 7; var birthday:Date = new Date(); // strict typing of parameters function welcome(firstName:String, age:Number){ } // strict typing of parameter and return value function square(x:Number):Number { var squared = x*x; return squared; }
Because you must use the var
keyword when strictly typing variable, you can't strictly type a global variable (see Scoping and declaring variables).
You can declare the data type of objects based on built-in classes (Button, Date, MovieClip, and so on) and on classes and interfaces that you create. For example, if you have a file named Student.as in which you define the Student class, you can specify that objects you create are of type Student:
var student:Student = new Student();
You can also specify that objects are of type Function or Void.
Using strict typing helps ensure that you don't inadvertently assign an incorrect type of value to an object. Flash checks for typing mismatch errors at compile time. For example, suppose you type the following code:
// in the Student.as class file class Student { var status:Boolean; // property of Student objects } // in a script var studentMaryLago:Student = new Student(); studentMaryLago.status = "enrolled";
When Flash compiles this script, a "Type mismatch" error is generated.
Another advantage of strict data typing is that Flash MX 2004 automatically displays code hints for built-in objects when they are strictly typed. For more information, see Strictly typing objects to trigger code hints.
Files published using ActionScript 1 do not respect strict data typing assignments at compile time. Thus, assigning the wrong type of value to a variable that you have strictly typed doesn't generate a compiler error.
var x:String = "abc" x = 12 ; // no error in ActionScript 1, type mismatch error in ActionScript 2
The reason for this is that when you publish a file for ActionScript 1, Flash interprets a statement such as var x:String = "abc" as slash syntax rather than as strict typing. (ActionScript 2.0 doesn't support slash syntax.) This behavior can result in an object that is assigned to a variable of the wrong type, causing the compiler to let illegal method calls and undefined property references pass through unreported.
Therefore, if you are implementing strict data typing, make sure you are publishing files for ActionScript 2.0.
![]() | |
![]() | |
![]() | |
![]() ![]() ![]() |