Strict data typing
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
// 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
global variable (see
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
to trigger code hints" on page
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
38
Chapter 2: ActionScript Basics
keyword when strictly typing variable, you can't strictly type a
var
"Scoping and declaring variables" on page
62.
keyword and post-colon syntax:
var
41).
"Strictly typing objects
Need help?
Do you have a question about the FLASH MX 2004 - ACTIONSCRIPT and is the answer not in the manual?