Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

flash - Actionscript - Obtain the name of the current function

I want to get the name of a function from inside that function. e.g.:

function blah() {
    //I want to get the string "blah" here, from the function's name
}

Or at least the Function object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use arguments.callee to get a reference to the current function.

I you want to get the function name, it is a bit trickier: All functions are treated as method closures (pieces of code which can be passed around as an argument), so they do not own a reference to an enclosing class type, nor do they have a "current name".

However, if (and only if) the method is public, and you want to get the method name from the class declaration of an instance object containing the method, you can use describeType:

public function someFunction() : void {
    var callee:Function = arguments.callee;
    trace (getFunctionName(callee, this)); // ==> someFunction
}

private function someOtherFunction() : void {
    var callee:Function = arguments.callee;
    trace (getFunctionName(callee, this)); // ==> not found
}

private function getFunctionName (callee:Function, parent:Object):String {
    for each ( var m:XML in describeType(parent)..method) {
        if ( parent[m.@name] == callee) return m.@name;
    }
    return "not found";
}

Note that this would not work when you call someFunction() from a constructor, because the object is not fully instantiated - describeType(this) in a constructor would cause a compilation error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...