【问题标题】:How do I get the name of the function that calls a method?如何获取调用方法的函数的名称?
【发布时间】:2015-01-15 14:29:16
【问题描述】:

考虑下一个例子:

 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 strict 模式并尝试使用它,我会得到 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 函数。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以在函数体内使用它:

    arguments.callee.caller.toString()
    

    检查这个sn-p:

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

    更新

    如果使用strict mode,上述将不起作用

    请阅读this,以查看下面他的cmets 中提到的Alex K.。我不知道。

    【讨论】:

    • 在这种情况下他们不想要Test吗?
    • 我不同意这个答案。用户似乎只想要Test 而不是整个:function Test(){ Log(); }
    • @SpencerWieczorek 据我所知,这是不可能的。
    • @SpencerWieczorec 我只想要函数的名称,下面的答案正是我想要的。 (arguments.callee.caller.name),但我使用严格模式。所以,我可以使用它。
    【解决方案2】:

    这应该可以完成工作:

    arguments.callee.caller.name
    

    但要小心:'caller'、'callee' 和 'arguments' 属性不能在严格模式下使用,它们在 ES5 中已被弃用并在严格模式下被移除。

    【讨论】:

    • 小心:arguments 未被弃用。
    • @SpencerWieczorek:不
    • 你是正确的参数当然不会被弃用,而被调用者和调用者是。
    • Function.arguments 已折旧,arguments 未折旧
    • @SpencerWieczorek:问题在于答案声称arguments 已被弃用,而实际上并非如此。
    猜你喜欢
    • 2011-07-03
    • 2011-09-09
    • 2014-07-11
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多