有可能这样做吗:

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

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


当前回答

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

其他回答

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

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

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

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

foo() 
// Logs: "foo"

这里有一个可行的方法:

export function getFunctionCallerName (){
  // gets the text between whitespace for second part of stacktrace
  return (new Error()).stack.match(/at (\S+)/g)[1].slice(3);
}

然后在你们的测试中

import { expect } from 'chai';
import { getFunctionCallerName } from '../../../lib/util/functions';

describe('Testing caller name', () => {

    it('should return the name of the function', () => {
      function getThisName(){
        return getFunctionCallerName();
      }

      const functionName = getThisName();

      expect(functionName).to.equal('getThisName');
    });

  it('should work with an anonymous function', () => {


    const anonymousFn = function (){
      return getFunctionCallerName();
    };

    const functionName = anonymousFn();

    expect(functionName).to.equal('anonymousFn');
  });

  it('should work with an anonymous function', () => {
    const fnName = (function (){
      return getFunctionCallerName();
    })();

    expect(/\/util\/functions\.js/.test(fnName)).to.eql(true);
  });

});

注意,只有当测试位于/util/functions中时,第三个测试才会工作

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

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

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

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

这是伊戈尔·奥斯特鲁莫夫回答的一个变体:

如果你想使用它作为参数的默认值,你需要考虑对'caller'的二级调用:

function getFunctionsNameThatCalledThisFunction()
{
  return getFunctionsNameThatCalledThisFunction.caller.caller.name;
}

这将动态地允许多个函数中的可重用实现。

getFunctionsNameThatCalledThisFunction()函数 { 返回getFunctionsNameThatCalledThisFunction.caller.caller.name; } (myFunctionName = getFunctionsNameThatCalledThisFunction()) { 警报(myFunctionName); } //弹出"foo" 函数foo () { 酒吧(); } 乌鸦()函数 { 酒吧(); } foo (); 乌鸦();

如果你也想要文件名,这里是使用F-3000在另一个问题上的答案的解决方案:

function getCurrentFileName()
{
  let currentFilePath = document.scripts[document.scripts.length-1].src 
  let fileName = currentFilePath.split('/').pop() // formatted to the OP's preference

  return fileName 
}

function bar(fileName = getCurrentFileName(),  myFunctionName = getFunctionsNameThatCalledThisFunction())
{
  alert(fileName + ' : ' + myFunctionName);
}

// or even better: "myfile.js : foo"
function foo()
{
  bar();
}

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