2009-04-02 10 views

Respuesta

2

¿El nombre? No, no puedes. Sin embargo, lo que puedes hacer es probar la referencia. Algo como esto:

function foo() 
{ 
} 

function bar() 
{ 
} 

function a(b : Function) 
{ 
    if(b == foo) 
    { 
     // b is the foo function. 
    } 
    else 
    if(b == bar) 
    { 
     // b is the bar function. 
    } 
} 
0

¿Está buscando simplemente una referencia para que pueda volver a llamar a la función? Si es así, intente configurar la función a una variable como referencia. var lastFunction: Function;

var func:Function = function test():void 
{ 
    trace('func has ran'); 
} 

function A(pFunc):void 
{ 
    pFunc(); 
    lastFunction = pFunc; 
} 
A(func); 

Ahora, si necesita hacer referencia a la última función ejecutada, puede hacerlo simplemente llamando a lastFunction.

No estoy seguro exactamente de lo que está tratando de hacer, pero quizás esto pueda ayudar.

15

utilizo el siguiente:

private function getFunctionName(e:Error):String { 
    var stackTrace:String = e.getStackTrace();  // entire stack trace 
    var startIndex:int = stackTrace.indexOf("at ");// start of first line 
    var endIndex:int = stackTrace.indexOf("()"); // end of function name 
    return stackTrace.substring(startIndex + 3, endIndex); 
} 

Uso:

private function on_applicationComplete(event:FlexEvent):void { 
    trace(getFunctionName(new Error()); 
} 

Salida: FlexAppName/on_applicationComplete()

Más información acerca de la técnica se puede encontrar en el sitio de Alex:

http://blogs.adobe.com/aharui/2007/10/debugging_tricks.html

+4

Yo diría que tener cuidado de usar esto en su el diseño del sistema, es un código bastante frágil, como en, si alguien en Adobe decide reformular su mensaje de seguimiento de pila, su código se rompe. Entonces, quizás pregúntese si realmente necesita saber el nombre de las funciones para resolver el problema que tiene. –

+0

De acuerdo. Lo uso principalmente para la depuración, y no tanto últimamente ya que puedo acceder al código con Flex Builder Pro. –

+0

idea genial ... pero solo funciona en el reproductor de depuración !!! si eso es suficiente, está bien, pero en general esto todavía no resuelve el problema ... – back2dos

0

No sé si ayuda, pero puede obtener una referencia a la persona que llama de la función que arguments (hasta donde yo sé, solo en ActionScript 3).

+0

No puede obtener la persona que llama, pero tiene una referencia al destinatario. – joshtynjala

3

Heres una implementación simple

public function testFunction():void { 
     trace("this function name is " + FunctionUtils.getName()); //will output testFunction 
    } 

Y en un archivo llamado FunctionUtils pongo esto ...

/** Gets the name of the function which is calling */ 
    public static function getName():String { 
     var error:Error = new Error(); 
     var stackTrace:String = error.getStackTrace();  // entire stack trace 
     var startIndex:int = stackTrace.indexOf("at ", stackTrace.indexOf("at ") + 1); //start of second line 
     var endIndex:int = stackTrace.indexOf("()", startIndex); // end of function name 

     var lastLine:String = stackTrace.substring(startIndex + 3, endIndex); 
     var functionSeperatorIndex:int = lastLine.indexOf('/'); 

     var functionName:String = lastLine.substring(functionSeperatorIndex + 1, lastLine.length); 

     return functionName; 
    } 
6

He estado probando las soluciones sugeridas, pero me encontré con problemas con todos ellos en ciertos puntos. Principalmente debido a las limitaciones de los miembros dinámicos o fijos. Hice un poco de trabajo y combiné ambos enfoques. Eso sí, funciona solo para miembros públicamente visibles; en todos los demás casos, se devuelve null.

/** 
    * Returns the name of a function. The function must be <b>publicly</b> visible, 
    * otherwise nothing will be found and <code>null</code> returned.</br>Namespaces like 
    * <code>internal</code>, <code>protected</code>, <code>private</code>, etc. cannot 
    * be accessed by this method. 
    * 
    * @param f The function you want to get the name of. 
    * 
    * @return The name of the function or <code>null</code> if no match was found.</br> 
    *   In that case it is likely that the function is declared 
    *   in the <code>private</code> namespace. 
    **/ 
    public static function getFunctionName(f:Function):String 
    { 
     // get the object that contains the function (this of f) 
     var t:Object = getSavedThis(f); 

     // get all methods contained 
     var methods:XMLList = describeType(t)[email protected]; 

     for each (var m:String in methods) 
     { 
      // return the method name if the thisObject of f (t) 
      // has a property by that name 
      // that is not null (null = doesn't exist) and 
      // is strictly equal to the function we search the name of 
      if (t.hasOwnProperty(m) && t[m] != null && t[m] === f) return m;    
     } 
     // if we arrive here, we haven't found anything... 
     // maybe the function is declared in the private namespace? 
     return null;           
    } 
+0

Buen enfoque, pero 'getSavedThis()' funciona solo en versiones de depuración de flash player. – Art

+0

Gracias por esto, y en caso de que alguien más tenga problemas para encontrar los paquetes: import flash.utils.describeType; import flash.sampler.getSavedThis; – Hudson

Cuestiones relacionadas