动作脚本功能可以找到自己的名字吗?

12 actionscript actionscript-2 actionscript-3

给出以下内容

function A(b:Function)   { }
Run Code Online (Sandbox Code Playgroud)

如果函数A(),我们可以确定作为参数'b'传入的函数的名称吗?AS2和AS3的答案有何不同?

小智 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);
}
Run Code Online (Sandbox Code Playgroud)

用法:

private function on_applicationComplete(event:FlexEvent):void {
    trace(getFunctionName(new Error());
}
Run Code Online (Sandbox Code Playgroud)

输出:FlexAppName/on_applicationComplete()

有关该技术的更多信息,请访问Alex的网站:

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

  • 我会说在你的系统设计中小心使用它,这是非常脆弱的代码,如果有人在Adobe决定改写他们的代码中断的堆栈跟踪消息.所以也许问问自己,你是否真的需要知道函数名称来解决你遇到的问题. (4认同)

小智 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;                                        
    }
Run Code Online (Sandbox Code Playgroud)


Luk*_*uke 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.
   }
}
Run Code Online (Sandbox Code Playgroud)