简体   繁体   English

是否可以从函数内部获取类或类名?

[英]Is it possible to get the class or class name from inside a function?

I'm trying to write debugging tools and I would like to be able to get the class name of the caller. 我正在尝试编写调试工具,并且希望能够获得调用方的类名。 Basically, caller ID. 基本上是来电显示。

So if I have a method like so, I want to get the class name: 因此,如果我有类似的方法,我想获取类名称:

public function myExternalToTheClassFunction():void {
   var objectFunction:String = argument.caller; // is functionInsideOfMyClass
   var objectFunctionClass:Object = argument.caller.this;
   trace(object); // [Class MyClass]
}

public class MyClass {

   public function functionInsideOfMyClass {
       myExternalToTheClassFunction();
   }
}

Is there anything like this in JavaScript or ActionScript3? JavaScript或ActionScript3中是否有类似的东西? FYI AS3 is based on and in most cases interchangeable with JS. FYI AS3基于JS,并且在大多数情况下可以与JS互换。

For debugging purposes you can create an error then inspect the stack trace: 出于调试目的,您可以创建一个错误,然后检查堆栈跟踪:

var e:Error = new Error();
trace(e.getStackTrace());

Gives you: 给你:

 Error
     at com.xyz::OrderEntry/retrieveData()[/src/com/xyz/OrderEntry.as:995]
     at com.xyz::OrderEntry/init()[/src/com/xyz/OrderEntry.as:200]
     at com.xyz::OrderEntry()[/src/com/xyz/OrderEntry.as:148]

You can parse out the "caller" method from there. 您可以从此处解析“调用方”方法。

Note that in some non-debug cases getStackTrace() may return null . 请注意,在某些非调试情况下, getStackTrace()可能返回null

Taken from the documentation : 来自文档

Unlike previous versions of ActionScript, ActionScript 3.0 has no arguments.caller property. 与以前的ActionScript版本不同,ActionScript 3.0没有arguments.caller属性。 To get a reference to the function that called the current function, you must pass a reference to that function as an argument. 要获得对调用当前函数的函数的引用,必须将对该函数的引用作为参数传递。 An example of this technique can be found in the example for arguments.callee . 可以在arguments.callee的示例中找到此技术的示例。

ActionScript 3.0 includes a new ...(rest) keyword that is recommended instead of the arguments class. ActionScript 3.0包括一个新的...(rest)关键字,而不是arguments类,建议使用。

Try to pass the Class name as argument: 尝试将Class名称作为参数传递:

Class Code: 班级代码:

package{

    import flash.utils.getQualifiedClassName;

    public class MyClass {

        public function functionInsideOfMyClass {

            myExternalToTheClassFunction( getQualifiedClassName(this) );

        }

    }

}

External Code: 外部代码:

public function myExternalToTheClassFunction(classname:String):void {

    trace(classname); // MyClass

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM