| Object.toString( ) Method | Flash 5 |
| the value of the object, as a string |
An internally defined string that describes or otherwise represents the object.
The toString( ) method returns a string description for someObject. The ECMA-262 specification states that, by default, Object.toString( ) should return the expression:
"[object " + class + "]"
where class is the internally defined name of the class to which someObject belongs. In practice, some ActionScript classes overwrite the default toString( ) method of Object in order to provide more meaningful information about each instance of the class. For those classes that don't provide a custom toString( ) method, ActionScript does not provide the individual class name. So, the default toString( ) method for instances of most classes returns:
[object Object]
The ActionScript interpreter automatically invokes the toString( ) method whenever someObject is used in a string context. For example:
x = new Object(); trace(x); // Displays: "[object Object]"
We can implement a custom toString( ) method when constructing our own classes. For example, the Date.toString( ) method returns the date and time; the Array.toString( ) method returns a comma-separated list of array elements; and the Number.toString( ) method returns a string version of the number.
This example shows how to provide a custom toString( ) method for the Ball class that we created in Chapter 12:
// Make the Ball constructor
function Ball (radius, color, xPosition, yPosition) {
this.radius = radius;
this.color = color;
this.xPosition = xPosition;
this.yPosition = yPosition;
}
// Add a custom toString() method
Ball.prototype.toString = function () {
return "A ball with the radius " + this.radius;
};
// Create a new Ball object
myBall = new Ball(6, 0x00FF00, 145, 200);
// Now check myBall's string value
trace(myBall); // Displays: "A ball with the radius 6"
Array.toString( ), Date.toString( ), Number.toString( ), Object.valueOf( )