问题描述
有没有人知道是否有办法获取JavaScript函数名称。例如,我得到了一个函数,如
Does anyone know if there is a way to get JavaScript function name. For example I got a function like
function test1(){
alert(1);
}
我的脑袋里有它。然后我创建一个对象obj1并将我的函数放在那里
I have it in my head section. Then I create an object obj1 and put my function there
obj1.func = test1;
当我在obj1对象中调用方法时,我是否有办法获取我的函数名称(test1) )除了解析函数的源( this.func.toString()
)之外,在此方法内部。
When I call a method in obj1 object, do I have any way to get my function name (test1) inside of this method, except parsing the source (this.func.toString()
) of the function.
推荐答案
function test() { alert(arguments.callee.name); }
b = test;
b();
输出test(在Chrome,Firefox和Safari中)。但是, arguments.callee.name
只能从 inside 函数中获得。
outputs "test" (in Chrome, Firefox and probably Safari). However, arguments.callee.name
is only available from inside the function.
如果您想从外部获取名称,您可以解析它:
If you want to get name from outside you may parse it out of:
b.toString();
但我认为函数对象的name属性可能是你需要的:
but I think name property of function object might be what you need:
alert(b.name);
然而这对于IE和Opera来说似乎不起作用所以你可以手动解析它们浏览器。
this however does not seem work for IE and Opera so you are left with parsing it out manually in those browsers.
这篇关于在JavaScript中获取函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!