[编辑]
我在代码中犯了一个错误来支持for each
循环,编辑来解决这个问题。
根据该类的文档Proxy
,我编写了这个示例。我以前从未做过,而且实现似乎有点奇怪。但是这段代码主要来自文档,并且可以正常工作:您可以在扩展的类上使用for each
循环或循环。for in
Proxy
主类:
package
{
import flash.display.Sprite;
public class Main extends Sprite
{
public function Main():void
{
var obj:MyClass = new MyClass();
trace("for in loop output:");
for (var propertyName:String in obj)
{
trace("property: " + propertyName + " value: " + obj[propertyName]);
}
trace("for each loop output:")
for each (var item:Object in obj)
{
trace("current item: " + item);
}
}
}
}
扩展类Proxy
:
package
{
import flash.display.Sprite;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
use namespace flash_proxy;
public class MyClass extends Proxy
{
protected var _target:Object = { property1: property1, property2: property2, property3: property3, property4: property4 };
protected var _item:Array;
public function MyClass()
{
}
override flash_proxy function nextNameIndex (index:int):int {
// initial call
if (index == 0)
{
_item = new Array();
for (var x:* in _target)
{
_item.push(x);
}
}
if (index < _item.length)
{
return index + 1;
}
else
{
return 0;
}
}
override flash_proxy function nextName(index:int):String
{
return _item[index - 1];
}
override flash_proxy function nextValue(index:int):*
{
return _target[ _item[index -1] ];
}
override flash_proxy function getProperty(name:*):*
{
return _target[name];
}
public var property1:String = "Hi";
public var property2:Boolean = true;
public var property3:Object = { a: 1, b: false };
public var property4:Sprite;
}
}
控制台输出:
for in loop output:
property: property2 value: true
property: property4 value: null
property: property1 value: Hi
property: property3 value: [object Object]
for each loop output:
current item: true
current item: null
current item: Hi
current item: null
在进一步查看文档时,Proxy
该类的实际实现可能还需要实现Proxy
该类的setProxy()
方法。