Can I assign a getter function to a variable in AS3?
I can do
function yea ():int {
...
}
var cool:Function=yea;
I don't know how to do something like
f开发者_Python百科unction get wat ():int {
...
}
var mmmh:Function=wat; // this (tries to) assign the wat returned value
Well, the only way I know is capturing getter/setter references from inside of them with arguments.callee
. But that's a rather weird thing to do. :)
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.getTimer;
public class GetterTest extends Sprite
{
private var getterRef:Function;
private var setterRef:Function;
private var testValue:int = 0;
public function GetterTest()
{
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
}
private function onMouseDown(event:Event):void
{
if (getterRef != null) {
setterRef(getTimer());
trace("references: test = ", getterRef());
} else {
test = getTimer();
trace("direct: test = ", test);
}
}
private function get test():int
{
trace("TEST! getter");
getterRef = arguments.callee;
return testValue;
}
private function set test(value:int):void
{
trace("TEST! setter");
setterRef = arguments.callee;
testValue = value;
}
}
}
While the above works, I think the correct answer to your question is "don't". :)
you could save the name of the getter as a string var fn:String = "wat"
and then use it later to retrieve the return value of the method with myObjectFromClass[fn]
.
I am not sure what is that you are trying to accomplish.
If you just want to keep a reference to the getter, you could just wrap it in a closure function.
var mmh:Function = function():int { return wat; };
精彩评论