原文地址在此
在Actionscript3中,你可以从Proxy类继承(extend)一个类来重写(override)许多语言级别的操作行为,这使其成为一个对高级开发而言有价值的工具.然而,他们比密封类(sealed class)慢得多,所以当需要高性能的情况下要小心使用.
Proxy允许你重写:
// function calls foo.bar(1, 2) => foo.callProperty('bar', 1, 2) // property get foo.bar foo['bar'] => foo.getProperty('bar') // property set foo.bar = 123 foo['bar'] = 123 => foo.setProperty('bar', 123) // property delete delete foo.bar delete foo['bar'] => foo.deleteProperty('bar') // in operator 'bar' in foo => foo.hasProperty('bar') // descendant operator foo..bar => foo.getDescendants('bar')Proxy也允许你使用nextNameIndex,nextName和nextValue重写for..in和for each..in循环的操作(handling).这是for..in循环
for(var key:String in foo) { trace(key); }对于proxy就等价于
var i:int = 0; while(true) { var index:int = foo.nextNameIndex(i); if(index == 0) break; var key:String = foo.nextName(index); trace(key); i++; }类似的,这里是for each..in循环
for each(var value:* in foo) { trace(value); }对于proxy就等价于
var i:int = 0; while(true) { var index:int = foo.nextNameIndex(i); if(index == 0) break; var value:* = foo.nextValue(index); trace(value); i++; }这是一个实现了这些方法的存根类(stub class)例子
package { import flash.utils.Proxy; import flash.utils.flash_proxy; public class ExampleProxy extends Proxy { private var items:Array; public function ExampleProxy():void { items = []; } override flash_proxy function deleteProperty(name:*):Boolean { return delete items[name]; } override flash_proxy function getProperty(name:*):* { return items[name]; } override flash_proxy function hasProperty(name:*):Boolean { return name in items; } override flash_proxy function nextNameIndex(index:int):int { if(index > items.length) return 0; return index + 1; } override flash_proxy function nextName(index:int):String { return String(index - 1); } override flash_proxy function nextValue(index:int):* { return items[index - 1]; } } }