AS3 - 返回一个类的属性,而不是类本身 [英] AS3 - Returning a property of a class rather than the class itself
问题描述
在ActionScript 3中,也有一些类,将重新present一个值,而不是类本身。这是很难解释正确了我的意思,所以拿这个例子:
In ActionScript 3, there are some classes that will represent a value rather than the class itself. It's hard to explain properly what I mean, so take this example:
var str:String = "something";
var mc:MovieClip = new MovieClip();
trace(str); // something
trace(mc); // [object MovieClip]
您会发现,第一个跟踪输出数值,而不是 [对象字符串]
。 Ontop此,我仍然可以使用字符串
,像这样的方法:
You'll notice that the first trace outputs a value, rather than [object String]
. Ontop of this, I can still make use of methods of String
, like this:
var ar:Array = str.split('s');
尽管在某种程度上,你几乎可以读取上面:
Even though in a way you could almost read the above as:
"something".split('s');
我有一个类 AvLevelData code>有与级别的数据处理(这基本上是一个字符串)的一些方法。目前有一个属性
数据:字符串
从而重新presents核心层的数据。
I have a class AvLevelData
that has some methods that deal with level data (which is essentially a String). At the moment there is a property data:String
which represents the core level data.
我的问题是 - 我可以复制该字符串的行为,当我跟踪或分配 AvLevelData code>的实例,其结果实际上是字符串
数据
。
The question I have is - can I replicate the behaviour of String in that when I trace or assign an instance of AvLevelData
, the result is actually the String data
.
例如,在现阶段,我需要去:
For example, at the moment I need to go:
var levelData:AvLevelData = new AvLevelData();
trace(levelData.data);
要获取数据。我反而希望能够简单地做到以下几点:
To get the data. I instead want to be able to simply do the following:
var levelData:AvLevelData = new AvLevelData();
trace(levelData); // some level data string
这可能吗?
推荐答案
如果您wan't你的对象描绘出自己制作的字符串,则必须实施的toString()
在函数的 AvLevelData code>类。
If you wan't your object to trace out your own fabricated string then you must implement a toString()
function on your AvLevelData
class.
在上面的例子中,影片剪辑
跟踪输出: [对象的MovieClip]
;这个来自默认的的toString()
实施对象
(在的Object.prototype <发现/ code>)。请注意,不能覆盖
的toString()
,因为它只存在于对象的原型
(的AS2 / Javascript的残余世界),所有你需要做的就是提供自己的名称相同。例如:
In your example above, the MovieClip
trace outputs: [Object MovieClip]
; this comes from the default toString()
implementation for Object
(found on Object.prototype
) . Note, you cannot override toString()
as it only exists on the prototype of Object
(remnants of the AS2/Javascript world), all you need to do is provide your own implementation with the same name. For instance:
public function toString():String {
return "MyCustomObjectString";
}
这篇关于AS3 - 返回一个类的属性,而不是类本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!