一个 ActionScript 函数能否找出自己的名称?

12

给定以下代码:

function A(b:Function)   { }

如果函数A()中,我们将函数名作为参数'b'传递进来,那么我们能否确定传入的函数名?这个答案在AS2和AS3中有所不同吗?

7个回答

15

我使用以下内容:

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


4
在你的系统设计中使用这段代码时需要小心,因为它非常脆弱。如果Adobe的某个人决定重构他们的堆栈跟踪消息,你的代码就会出问题。因此,也许要问问自己是否真的需要知道函数名来解决你所面临的问题。 - BefittingTheorem
同意。我主要用它来调试,最近使用不太频繁,因为我可以使用Flex Builder Pro逐步执行代码。 - user56512
非常酷的想法...但只在调试播放器中有效!!!如果这足够了,那就好,但总的来说这仍然没有解决问题.... - back2dos
使用Air 3.5和Flash 11.5,现在可以在发布版本中获取堆栈跟踪。我同意这种方法存在风险 - 堆栈跟踪字符串格式的微小更改可能会轻易地破坏代码,但它确实有效,并且效果很好。 - Atorian

6

我一直在尝试建议的解决方案,但在某些时候所有的解决方案都遇到了麻烦。主要是由于固定或动态成员的限制。我做了一些工作,将两种方法结合起来。请注意,它仅适用于公开可见的成员 - 在所有其他情况下返回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)..method.@name;

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

这是一个不错的方法,但 getSavedThis() 只在 Flash Player 的调试版本中有效。 - Art
谢谢您提供这个信息,如果其他人也遇到了找不到包的问题: import flash.utils.describeType; import flash.sampler.getSavedThis; - Hudson

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

2
名称?不行,你不能。但是你可以测试引用。像这样:
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

你只是想要一个参考,以便之后可以再次调用函数吗?如果是这样,请尝试将函数设置为变量作为参考。 var lastFunction: Function;

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

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

现在,如果您需要引用上次运行的函数,只需调用lastFunction即可。
我不确定您想要做什么,但也许这可以帮助您。

0

一般情况下,使用 toString()matcharguments.callee 结合使用:

function foo(){return arguments.callee.toString().match(/\s\w+/).toString()}

参考资料


0

我不知道这是否有帮助,但可以获取调用函数的引用参数(据我所知,仅适用于ActionScript 3)。


你无法获取调用者,但你确实有被调用者的引用。 - Josh Tynjala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接