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

// 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://kangax.github.com/nfe/)。

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

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

其他回答

可以使用name属性获取函数名,除非使用匿名函数

例如:

var Person = function Person () {
  this.someMethod = function () {};
};

Person.prototype.getSomeMethodName = function () {
  return this.someMethod.name;
};

var p = new Person();
// will return "", because someMethod is assigned with anonymous function
console.log(p.getSomeMethodName());

现在让我们试试named function

var Person = function Person () {
  this.someMethod = function someMethod() {};
};

现在你可以使用

// will return "someMethod"
p.getSomeMethodName()

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

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

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

作为ECMAScript 6的一部分,你可以使用Function.name方法

function doSomething() {}

alert(doSomething.name); // alerts "doSomething"

我知道这是一个老问题,但最近我为了调试目的,在尝试装饰一些React组件的方法时,也遇到了一些类似的问题。正如人们所说,争论。调用者和实参。calllee在严格模式下是被禁止的,而在你的React编译中,这可能是默认开启的。你可以禁用它,或者我已经能够想出另一个hack,因为在React中所有的类函数都是命名的,你实际上可以这样做:

Component.prototype.componentWillMount = function componentWillMount() {
    console.log('Callee name: ', this.__proto__.constructor.toString().substr(0,30));
...
}

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

看到stacktrace.js