繁体   English   中英

从函数内部获取函数名称

[英]Get the name of the function from inside the function

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

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.name
arguments.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还提到支持这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM