如何获取调用方法的函数的名称?

时间:2015-01-15 14:29:17

标签: javascript

考虑下一个例子:

 function Test(){
    Log();
 }
 function Log(){
   console.log('Name of the called function');
 }

如何获取函数的名称,在本例中为Test(),在没有corse参数的情况下进入我的Log函数。

请考虑这种方式:

function Hello(){
Log(); //should return Hello
}
function Test(){
Log(); //should return Test
}
function World(){
Log(); //should return World
}

function Log(){
return NAME_OF_FUNCTION;
}

由于

更新:

我可以使用arguments.callee.name获取名称,但是,这不适用于严格模式,如果我删除de严格模式并尝试使用它,我得到clousure函数的名称而不是名称父方法..例如:

var Log = (function(){

function info(message){
console.log(arguments.callee) //This print function info(message){
}

return {
info:info
}
})();

function Test(){

Log.info("Some Message");

}

这是错误的,我需要Test函数的名称,而不是info函数。

2 个答案:

答案 0 :(得分:2)

你可以在你的功能体内使用它:

arguments.callee.caller.toString()

检查此代码段:



function Test(){
    Log();
}

function Log(){
    alert(arguments.callee.caller.toString());
}

Test();




<强>更新

如果使用strict mode,则上述工作。

请阅读this,在评论中查看下面提到的Alex K.。我不知道。

答案 1 :(得分:2)

这应该做的工作:

arguments.callee.caller.name

但请注意:&#39;来电者&#39;,&#39; callee&#39;和&#39;参数&#39; 属性不能在严格模式下使用,不推荐使用在ES5中并在严格模式下删除。