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

// 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();

当前回答

可以使用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()

其他回答

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

看到stacktrace.js

这将在ES5, ES6,所有浏览器和严格模式函数中工作。

下面是使用命名函数时的样子。

(function myName() {
  console.log(new Error().stack.split(/\r\n|\r|\n/g)[1].trim());
})();
at myName (<anonymous>:2:15)

这是一个匿名函数的样子。

(() => {
  console.log(new Error().stack.split(/\r\n|\r|\n/g)[1].trim());
})();
at <anonymous>:2:15

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

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

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

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

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

动态检索函数名(像魔术变量一样)的一个简单解决方案是使用作用域变量。

{
  function parent() {
    console.log(a.name);
  }; let a = parent
}
{
  function child() {
    console.log(a.name)
  }; let a = child
};

parent();//logs parent
child();//logs child

注意:嵌套函数不再是源元素,因此不会被提升。 而且,这种技术不能用于匿名函数。