有可能这样做吗:

myfile.js:
function foo() {
    alert(<my-function-name>);
    // pops-up "foo"
    // or even better: "myfile.js : foo"
}

我的堆栈中有Dojo和jQuery框架,所以如果它们中的任何一个使工作更容易,都可以使用它们。


当前回答

(function f() {
    console.log(f.name);  //logs f
})();

打印稿变化:

function f1() {} 
function f2(f:Function) {
   console.log(f.name);
}

f2(f1);  //Logs f1

注意仅适用于ES6/ES2015兼容引擎。更多信息请参见

其他回答

根据MDN

警告:ECMAScript (ES5)第5版禁止在严格模式下使用arguments.callee()。避免使用arguments.callee(),方法是给函数表达式一个名称,或者在函数必须调用自身的地方使用函数声明。

如上所述,这只适用于你的脚本使用“严格模式”。这主要是出于安全考虑,遗憾的是目前还没有替代方案。

对于非匿名函数

function foo()
{ 
    alert(arguments.callee.name)
}

但在错误处理程序的情况下结果应该是错误处理程序函数的名称,不是吗?

这应该做到:

var fn = arguments.callee.toString().match(/function\s+([^\s\(]+)/);
alert(fn[1]);

对于调用者,只需使用caller. tostring()。

由于arguments.callee.name是非标准的,并且在ECMAScript 5严格模式(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)中被禁止,动态检索函数名的一个简单解决方案[像魔术变量一样]是使用作用域变量和function .name属性。

{
  function foo() {
    alert (a.name);
  }; let a = foo
}
{
  function foo2() {
    alert(a.name)
  }; let a = foo2
};
foo();//logs foo
foo2();//logs foo2

注意:嵌套函数不再是源元素,因此不会被提升。而且,这种技术不能用于匿名函数。

arguments对象是一个局部变量,可在所有非箭头函数中使用。 可以使用函数的arguments对象来引用函数内部的参数。 它对调用函数的每个参数都有条目,第一个条目的索引为0。

所以你基本上可以使用arguments。callee。name但是在命名函数内部,像这样:

function i_have_a_name() {
    console.log(`My name is:`, arguments.callee.name)
}
> i_have_a_name()
My name is: i_have_a_name

不幸的是,它不能在箭头函数中使用:

const i_have_a_name = () => {
    console.log(`My name is:`, arguments.callee.name)
}
> i_have_a_name()
Uncaught ReferenceError: arguments is not defined
    at i_have_a_name (REPL3:2:32)

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments