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

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

当前回答

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

function doSomething() {}

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

其他回答

你不能。根据标准,函数没有名字(尽管mozilla有这样一个属性)——它们只能被赋值给有名字的变量。

还有你的评论:

// access fully qualified name (ie "my.namespace.myFunc")

在函数my.namespace. myfuncc . getfn

你所能做的就是返回一个由new

所以你可以说

var obj = new my.namespace.myFunc();
console.info(obj.constructor); //my.namespace.myFunc

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

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

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

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

你可以像这样使用构造函数名:

{your_function}.prototype.constructor.name

这段代码只是返回一个方法的名称。

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

arguments.callee.toString();

似乎正符合你的需要。

这将在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