开发者

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

开发者 https://www.devze.com 2022-12-11 17:33 出处:网络
i have a class that has something like this public class Foo { public var f:Function; public void method(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

精彩评论

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