views:

2149

answers:

3

Is there any way that I can reference a var or const as the default value for a function argument in actionscript 3.

I can define default values like null, string, int.

function a( b = null ) {
   blah...
}

But what I want to do is

function a( b = function(){} ) {
    blah...
}

which it seems like there would be a way to do. Presumably through a const

+3  A: 

Oddly enough it seems you can't do that, atleast I couldn't get it to work, it won't accept any references to static functions as a default value.

The best I could do was this:

public function myFunction(functionArgument:Function = null):void {
    if (functionArgument != null) {
     functionArgument();
    } else {
     defaultFunction();
    }
}

As a sidenote I just discovered that you in fact can declare functions like this:

public static const STATICFUNC:Function = function():void { trace("i'm static!") };

But that seems to work the same way as declaring them the sane way, so no luck there either.

grapefrukt
Isn't it more conventional to write : public static function STATICFUNC():void{ trace("Im static!");}
Theo.T
OOPS. Must be a mistake but there shouldn't be parenthesis after functionArgument() and defaultFunction() as we don't want the result of the function but a reference to the function itself ?
Theo.T
A: 

Parameter defaults must be compile-time constants, because the compiler has to put in the default value when the code is compiled. This means static functions, no matter how predictable they are, cannot be used as parameter defaults. Compile-time constants are values the compiler knows about by inspecting your code, but not actually running it.

bzlm
+1  A: 

I agree with grapefrukt.

But in case you want to create new objects at each call you can do this :

function myFunction(f:Function = null):void
{
    f = (f != null) ? f : function():void{ trace('new function'); }
}

or of course :

function myFunction(f:Function = null):void
{
    f = (f != null) ? f : defaultFunction; 
}

function defaultFunction():void
{
   trace('default function invoked')
}
Theo.T