如何从方法内部获取js方法名称

how to get js method name from inside the method

我想直接从这个方法体中获取当前方法名,我的代码不起作用:

var myFunction = function(){
    console.log(arguments.callee.name); // output must be "myFunction" 
}


This works excellently

function myFunction() {
    console.log(arguments.callee.name); // output is "myFunction" 
}

你对我有什么建议,有什么方法可以使这项工作成功吗? 我越来越多地搜索 google 但没有找到 smth。有帮助

函数是匿名的,没有名字。

要获取变量名,请遵循this answer

解决方案 1: 尝试创建一个具有 propertyobject,然后您 遍历 属性并显示 property.

的名称
var x = {
    myFunction : function(){      
    }
};

for(var variable in x)
{
    console.log(variable);
}

方案二: 我试图做出 解决方法 。我认为 property 是对象中的 first,我尝试显示 property.

的名称
var funcTest = function() {   
    for(var variable in this) {
        console.log(variable);
        break;
    }
} 

var x = {  myFunction : funcTest  };
x.myFunction(); // myFunction

var y = { secondFunction : funcTest }
y.secondFunction(); // secondFunction

解决方案是给函数一个名称

var myMethod = function myMethod () {    
    console.log(arguments.callee.name); // output is "myMethod"
};

我一点也不喜欢这种方式,但它在具体任务中有效