564
ActionScript classes
Example
This example shows the return value for toString() on a generic object:
var myObject:Object = new Object();
trace(myObject.toString()); // output: [object Object]
This method can be overridden to return a more meaningful value. The following examples
show that this method has been overridden for the built-in classes Date, Array, and Number:
// Date.toString() returns the current date and time
var myDate:Date = new Date();
trace(myDate.toString()); // output: [current date and time]
// Array.toString() returns the array contents as a comma-delimited string
var myArray:Array = new Array("one", "two");
trace(myArray.toString()); // output: one,two
// Number.toString() returns the number value as a string
// Because trace() won't tell us whether the value is a string or number
// we will also use typeof() to test whether toString() works.
var myNumber:Number = 5;
trace(typeof (myNumber)); // output: number
trace(myNumber.toString()); // output: 5
trace(typeof (myNumber.toString())); // output: string
The following example shows how to override
toString()
in a custom class. First create a
text file named
Vehicle.as
that contains only the Vehicle class definition and place it into your
Classes folder inside your Configuration folder.
// contents of Vehicle.as
class Vehicle {
var numDoors:Number;
var color:String;
function Vehicle(param_numDoors:Number, param_color:String) {
this.numDoors = param_numDoors;
this.color = param_color;
}
function toString():String {
var doors:String = "door";
if (this.numDoors > 1) {
doors += "s";
}
return ("A vehicle that is " + this.color + " and has " + this.nu
" " + doors);
}
}
// code to place into a FLA file
var myVehicle:Vehicle = new Vehicle(2, "red");
trace(myVehicle.toString());
Summary of Contents for FLASHLITE2 ACTIONSCRIPT-LANGUAGE
Page 1: ...Flash Lite 2 x ActionScript Language Reference...
Page 22: ...22 Contents...
Page 244: ...244 ActionScript language elements...
Page 760: ...760 ActionScript classes...