有可能这样做吗:

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

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


当前回答

根据MDN

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

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

其他回答

你所需要的很简单。 创建函数:

function getFuncName() {
   return getFuncName.caller.name
}

在此之后,无论何时你需要,你只需使用:

function foo() { 
  console.log(getFuncName())
}

foo() 
// Logs: "foo"

这应该做到:

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

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

2016年的信息是真实的。


函数声明的结果

歌剧的结果

>>> (function func11 (){
...     console.log(
...         'Function name:',
...         arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
... })();
... 
... (function func12 (){
...     console.log('Function name:', arguments.callee.name)
... })();
Function name:, func11
Function name:, func12

Chrome中的结果

(function func11 (){
    console.log(
        'Function name:',
        arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
})();

(function func12 (){
    console.log('Function name:', arguments.callee.name)
})();
Function name: func11
Function name: func12

NodeJS的结果

> (function func11 (){
...     console.log(
.....         'Function name:',
.....         arguments.callee.toString().match(/function\s+([_\w]+)/)[1])
... })();
Function name: func11
undefined
> (function func12 (){
...     console.log('Function name:', arguments.callee.name)
... })();
Function name: func12

不能在Firefox中工作。未经IE和Edge测试。


函数表达式的结果

NodeJS的结果

> var func11 = function(){
...     console.log('Function name:', arguments.callee.name)
... }; func11();
Function name: func11

Chrome中的结果

var func11 = function(){
    console.log('Function name:', arguments.callee.name)
}; func11();
Function name: func11

不工作在Firefox, Opera。未经IE和Edge测试。

注:

匿名函数没有意义去检查。 测试环境


~ $ google-chrome --version
Google Chrome 53.0.2785.116           
~ $ opera --version
Opera 12.16 Build 1860 for Linux x86_64.
~ $ firefox --version
Mozilla Firefox 49.0
~ $ node
node    nodejs  
~ $ nodejs --version
v6.8.1
~ $ uname -a
Linux wlysenko-Aspire 3.13.0-37-generic #64-Ubuntu SMP Mon Sep 22 21:28:38 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

既然你写了一个名为foo的函数,你知道它在myfile.js中,为什么你需要动态地获取这个信息?

也就是说,你可以在函数内部使用arguments.callee.toString()(这是整个函数的字符串表示),并regex出函数名的值。

下面是一个会吐出自己名字的函数:

function foo() {
    re = /^function\s+([^(]+)/
    alert(re.exec(arguments.callee.toString())[1]);             
}

这必须归入“世界上最丑陋的黑客”的范畴,但你看。

首先,打印当前函数的名称(就像在其他答案中一样)对我来说用处有限,因为您已经知道这个函数是什么!

然而,找出调用函数的名称对于跟踪函数可能非常有用。这是一个regexp,但使用indexOf会快大约3倍:

function getFunctionName() {
    var re = /function (.*?)\(/
    var s = getFunctionName.caller.toString();
    var m = re.exec( s )
    return m[1];
}

function me() {
    console.log( getFunctionName() );
}

me();