有可能这样做吗:

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

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


当前回答

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

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

然而,找出调用函数的名称对于跟踪函数可能非常有用。这是一个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();

其他回答

这里有一个可行的方法:

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中时,第三个测试才会工作

这应该做到:

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

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

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

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

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

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

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

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

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

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

foo() 
// Logs: "foo"

根据MDN

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

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