如何从函数内部访问函数名?

// parasitic inheritance
var ns.parent.child = function() {
  var parent = new ns.parent();
  parent.newFunc = function() {

  }
  return parent;
}

var ns.parent = function() {
  // at this point, i want to know who the child is that called the parent
  // ie
}

var obj = new ns.parent.child();

当前回答

看这里:http://www.tek-tips.com/viewthread.cfm?qid=1209619

arguments.callee.toString();

似乎正符合你的需要。

其他回答

您可以使用Error。堆栈来跟踪函数名和您在其中的确切位置。

看到stacktrace.js

你所做的就是将一个未命名的函数赋值给一个变量。您可能需要使用命名函数表达式(http://kangax.github.com/nfe/)。

var x = function x() {
    console.log( arguments.callee.name );
}
x();

但我不确定这有多跨浏览器;IE6有一个问题,使你的函数名泄漏到外部作用域。同时,参数。Callee已经弃用了,如果你使用严格模式,它会导致错误。

从正在运行的函数中获取函数名的简单方法。

函数x(){警报(this.name)}; x ()

对于支持Error的浏览器,可以使用这个选项。堆栈(可能不是全部)

function WriteSomeShitOut(){ 
  var a = new Error().stack.match(/at (.*?) /);
  console.log(a[1]);
} 
WriteSomeShitOut();

当然这是针对当前函数的,但你懂的。

在你编程的时候开心地流口水

试试Function.name吧

const func1 = function() {};

const object = {
  func2: function() {}
};

console.log(func1.name);
// expected output: "func1"

console.log(object.func2.name);
// expected output: "func2"