toString(Object.toString 方法)

public toString() : String

将指定对象转换为字符串然后返回它。

可用性:ActionScript 1.0、Flash Player 5

返回

String ― 一个字符串。

示例

此示例显示某个一般对象的 toString() 的返回值:

var myObject:Object = new Object();
trace(myObject.toString()); // output: [object Object]

可以覆盖此方法以返回一个更有意义的值。下面的示例说明已经针对内置类 Date、Array 和 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

下面的示例演示如何覆盖自定义类中的 toString()。首先创建一个名为 Vehicle.as 的文本文件(只包含 Vehicle 类定义)并将其置于 Configuration 文件夹中的 Classes 文件夹中。

// 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.numDoors + " " + doors);
}
}

// code to place into a FLA file
var myVehicle:Vehicle = new Vehicle(2, "red");
trace(myVehicle.toString());
// output: A vehicle that is red and has 2 doors

// for comparison purposes, this is a call to valueOf()
// there is no primitive value of myVehicle, so the object is returned
// giving the same output as toString().
trace(myVehicle.valueOf());
// output: A vehicle that is red and has 2 doors


Flash CS3

 

评论添加到页面后给我发送电子邮件 | 评论报告

当前页: http://livedocs.adobe.com/flash/9.0_cn/main/00002046.html