有可能这样做吗:

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

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


当前回答

下面代码段中的getMyName函数返回调用函数的名称。这是一个黑客,依赖于非标准的特性:Error.prototype.stack。注意,由Error.prototype.stack返回的字符串格式在不同的引擎中实现是不同的,所以这可能不会在任何地方都适用:

函数getMyName() { var e = new错误('dummy'); Var stack = e.stack .split(“\ n”)[2] // " at functionName(…)"“= >”functionName .replace (/ ^ \ s + \ s + (+ ?) \ s。+/g, '$1'); 返回栈 } 函数foo () { 返回getMyName () } 功能栏(){ 返回foo () } console.log (bar ())

关于其他解决方案:争论。严格模式下不允许使用callee,严格模式下不允许使用Function.prototype.calleris非标准的。

其他回答

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

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

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

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

另一个用例可以是在运行时绑定事件分派器:

MyClass = function () {
  this.events = {};

  // Fire up an event (most probably from inside an instance method)
  this.OnFirstRun();

  // Fire up other event (most probably from inside an instance method)
  this.OnLastRun();

}

MyClass.prototype.dispatchEvents = function () {
  var EventStack=this.events[GetFunctionName()], i=EventStack.length-1;

  do EventStack[i]();
  while (i--);
}

MyClass.prototype.setEvent = function (event, callback) {
  this.events[event] = [];
  this.events[event].push(callback);
  this["On"+event] = this.dispatchEvents;
}

MyObject = new MyClass();
MyObject.setEvent ("FirstRun", somecallback);
MyObject.setEvent ("FirstRun", someothercallback);
MyObject.setEvent ("LastRun", yetanothercallback);

这里的优点是dispatcher可以很容易地重用,并且不需要接收dispatcher队列作为参数,相反,它与调用名称一起隐含…

最后,这里给出的一般情况是“使用函数名作为参数,这样你就不必显式地传递它”,这在很多情况下可能是有用的,比如jquery animate()可选回调,或者在超时/间隔回调中,(即你只传递一个函数名)。

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

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

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

Try:

alert(arguments.callee.toString());

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

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

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

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

foo() 
// Logs: "foo"