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

时间:2015-03-17 05:28:58

标签: javascript

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

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已弃用,严格模式下无法使用 我正在寻找一种不被弃用的方法,并且在严格模式下工作。

1 个答案:

答案 0 :(得分:1)

试试这个......

console.log(myFunction.name);

请注意,IE尚未提及here