开发者

Generic way to get reference to a method's caller?

I have 2 classes representing 2 objects. From the "whoCalledMe" function, I want to find out what object called the function (without passing that information in as an argument). I've used a make-believe property, "caller", that would give me the reference I'm looking for. Is there a generic way I can get a refer开发者_Go百科ence to the caller from there?

package {
    public class ObjectCallingTheFunction {
        public var IDENTITY:String = "I'm the calling function!";

        public function ObjectCallingTheFunction() {
            var objectWithFunction:ObjectWithFunction = new ObjectWithFunction();
            objectWithFunction.whoCalledMe();
        }
    }
}

package {
    public class ObjectWithFunction {
        public function whoCalledMe ():void {
            trace(caller.IDENTITY); // Outputs: "I'm the calling function!"
        }
    }
}


It would help to know why you need this, because I have a feeling that you don't really. If the method is anonymous, you can bind the 'this' keyword by using .apply on the method:

var foo:Function = function(arg:int):void
{
    trace(this);
};

var bar:Object = {
    toString: function():String { return "bar"; }
};

var baz:Object = {
    toString: function():String { return "baz"; }
};

foo.apply(bar); // <-- Prints "bar"
foo.apply(baz); // <-- Prints "baz"

If the method is an instance method method however, it's a bound method and thus "this" will always point to the instance of the class it's declared in, no matter if you redefine it by using the apply method. If it's a static method, "this" doesn't make sense and the compiler will catch it.

Other than that, there's really no way short of declaring it as a parameter. There used to be a caller property on the arguments object, but it was deprecated when AS3 was released. You can get a reference to the function itself through arguments.callee, but that's not really what you asked for.


In AS3 you can throw an error and then parse the Stack Trace to find out detailed informations.

You can check here for an example:

http://www.actionscript-flash-guru.com/blog/18-parse-file-package-function-name-from-stack-trace-in-actionscript-as3

If you want to find the called function's name you can follow this example:

http://www.flashontherocks.com/2010/03/12/getting-function-name-in-actionscript-3/


I guess you want to know the caller in debug purpose. if so I would recommend setting a breakpoint in the method/function instead of tracing. When the code breaks you can backtrace the caller and a lot more. Works in Flash IDE as well as Flashbuilder. Google "as3 breakpoints" if you are new to breakpoints.


Here is the official Adobe article on using arguments.callee

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/arguments.html

It includes sample code.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜