gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:08:19 27 4
gpt4 key购买 nike

考虑下一个例子:

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

如何在没有 corse 参数的情况下将函数名称(在本例中为 Test())获取到我的 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 来获取名称,但是,这在严格模式下不起作用,如果我删除严格模式并尝试使用它,我会得到 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");

}

这是错误的,我需要测试函数的名称,而不是信息函数。

最佳答案

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

arguments.callee.caller.toString()

检查这个片段:

function Test(){
Log();
}

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

Test();

更新

如果使用严格模式,上述将工作。

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

关于javascript - 如何获取调用方法的函数的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27965657/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com