有可能这样做吗:

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

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


当前回答

这里有一句话:

    arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '')

是这样的:

    function logChanges() {
      let whoami = arguments.callee.toString().split('\n')[0].substr('function '.length).replace(/\(.*/, "").replace('\r', '');
      console.log(whoami + ': just getting started.');
    }

其他回答

Try:

alert(arguments.callee.toString());

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

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

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

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

这是我在这里看到的一些回应的组合。(在FF, Chrome, IE11测试)

function functionName() 
{
   var myName = functionName.caller.toString();
   myName = myName.substr('function '.length);
   myName = myName.substr(0, myName.indexOf('('));
   return myName;
}

function randomFunction(){
    var proof = "This proves that I found the name '" + functionName() + "'";
    alert(proof);
}

调用randomFunction()将提醒包含函数名的字符串。

JS小提琴演示:http://jsfiddle.net/mjgqfhbe/

这里有一个可行的方法:

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