开发者

how to use the Function type in AS3 (var f:Function) for a method f(s:String)

i have a class that has something like this

public class Foo {
public var f:Function;
public void method(s:String)
{
  f.invoke(s);
}

}

so i need to assign to the f a function that takes an a开发者_开发技巧rgument f(s), something like

myFoo.f = thefunction
function(s:String)

how to do all this, so it will work correctly ?


Just to add a nice example:

        import mx.events.FlexEvent;
        public var f:Function;

        protected function application1_creationCompleteHandler(event:FlexEvent):void
        {
            f = addSmile;
            method(' my string');
            f = addFrown;
            method(' my string');

            // Or you can do it straight like this:
            f(' my string');


            // Or alternatively write a function for replacing f
            makeF(addSmile);
            f(' my string');
        }

        public function method(s:String):void
        {
            f(s);
        }

        private function addSmile(s:String):void
        {
            trace (s+' :)');    
        }
        private function addFrown(s:String):void
        {
            trace (s+' :(');    
        }                       

        protected function makeF(newF:Function):void
        {
            f= newF;
        }

will output

 my string :)
 my string :(
 my string :(
 my string :)


if you are meaning, how to do anonymous functions...

myFoo.f = function( s : String ) {
    //do Stuff to string
}

Then you can use the code you have above.


You should not point anywhere, that your function takes one String argument. If it takes int, or takes 2 arguments, - it would be a runtime error.


myFoo.f = myFunction;

public void function myFunction(s: String): void
{
}

public class Foo {
    public var f:Function;
    public void method(s:String)
    {
        f(s);
    }
}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜