Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...