从函数内部获取函数的名称

Get the name of the function from inside the function

本文关键字:函数 获取 内部      更新时间:2023-09-26

是否可以从函数内部获取函数的名称?
例:

function myFunction() {
  // console.log the name of this function without knowing/specifying what the name is
  // otherwise console.log('myFunction was called'); is 
  // more obvious (and better supported) than console.log(myFunction.name);
  // console.log(arguments.callee.name); works but not in strict mode and is deprecated
}

参考:

Function.namearguments.callee

更新:
从评论和回答来看,似乎完全错过了重点。
我修改了示例以使其更清晰。

更新 2:
似乎仍然存在歧义...下面是调试过程的示例:

function one() {
  console.log(arguments.callee.name + ' was called'); // one was called
  // reset of the code
}
function two() {
  console.log(arguments.callee.name + ' was called'); // two was called
  // reset of the code
}
function three() {
  console.log(arguments.callee.name + ' was called'); // three was called
  // reset of the code
}
function four() {
  console.log(arguments.callee.name + ' was called'); // four was called
  // reset of the code
}
function five() {
  console.log(arguments.callee.name + ' was called'); // five was called
  // reset of the code
}

arguments.callee.name已弃用,在严格模式下不可用。
我正在寻找一种未弃用且在严格模式下工作的方法。

试试这个...

console.log(myFunction.name);

请注意,IE尚不支持此功能,如此处所述