给出以下内容
function A(b:Function) { }
如果函数A(),我们可以确定作为参数'b'传入的函数的名称吗?AS2和AS3的答案有何不同?
我使用以下内容:
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
我一直在尝试建议的解决方案,但我在某些方面遇到了所有问题.主要是因为固定或动态成员的限制.我做了一些工作并结合了两种方法.请注意,它仅适用于公开可见的成员 - 在所有其他情况下,返回null.
/** * Returns the name of a function. The function must be publicly visible, * otherwise nothing will be found andnull
returned.Namespaces like *internal
,protected
,private
, etc. cannot * be accessed by this method. * * @param f The function you want to get the name of. * * @return The name of the function ornull
if no match was found. * In that case it is likely that the function is declared * in theprivate
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; }