简体   繁体   中英

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? FYI AS3 is based on and in most cases interchangeable with 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 .

Taken from the documentation :

Unlike previous versions of ActionScript, ActionScript 3.0 has no arguments.caller property. 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 .

ActionScript 3.0 includes a new ...(rest) keyword that is recommended instead of the arguments class.

Try to pass the Class name as argument:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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