Actionscript - 获取当前函数的名称 [英] 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
}
或者至少是 Function 对象?
Or at least the Function object?
推荐答案
使用 arguments.callee 获取对当前函数的引用.
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".
但是,如果(并且仅如果)该方法是公共的,并且您想从包含该方法的实例对象的类声明中获取方法名称,则可以使用 describeType:
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";
}
请注意,当您从构造函数调用 someFunction()
时,这将不起作用,因为对象未完全实例化 - 构造函数中的 describeType(this)
会导致编译错误.
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.
这篇关于Actionscript - 获取当前函数的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!