Подтвердить что ты не робот

Может ли функция actioncript узнать свое имя?

учитывая следующее

function A(b:Function)   { }

Если функция A(), мы можем определить имя функции, передаваемой в качестве параметра 'b'? Ответ отличается от AS2 и AS3?

4b9b3361

Ответ 1

Я использую следующее:

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);
}

Использование:

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

Вывод: FlexAppName/on_applicationComplete()

Более подробную информацию о технике можно найти на сайте Alex:

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

Ответ 2

Я пробовал предлагаемые решения, но я столкнулся с проблемами со всеми из них в определенные моменты. В основном из-за ограничений как для фиксированных, так и для динамических членов. Я проделал определенную работу и объединил оба подхода. Имейте в виду, что он работает только для общедоступных членов - во всех остальных случаях возвращается 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;                                        
    }

Ответ 3

Вот простая реализация

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

И в файле с именем FunctionUtils я помещаю это...

    /** 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;
    }

Ответ 4

Название? Нет, ты не можешь. Однако вы можете проверить ссылку. Что-то вроде этого:

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.
   }
}

Ответ 5

Вы просто ищете ссылку, чтобы снова вызвать функцию после? Если да, попробуйте установить функцию в качестве ссылки.   var lastFunction: Function;

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

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

Теперь, если вам нужно ссылаться на последнюю запущенную функцию, вы можете сделать это просто через вызов lastFunction.

Я не уверен точно, что вы пытаетесь сделать, но, возможно, это может помочь.

Ответ 6

Я не знаю, помогает ли это, но может получить ссылку на вызывающего функцию, которая arguments (как далеко как я знаю только в ActionScript 3).