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

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

当前回答

如果我明白你想要做什么,这就是我在函数构造函数中所做的。

if (!(this instanceof arguments.callee)) {
    throw "ReferenceError: " + arguments.callee.name + " is not defined";
}

其他回答

这可能对你有用:

function foo() { bar(); }

function bar() { console.log(bar.caller.name); }

如果从匿名函数调用,运行foo()将输出“foo”或未定义。

它也适用于构造函数,在这种情况下,它将输出调用构造函数的名称(例如“Foo”)。

更多信息请访问:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

他们声称这是不标准的,但所有主流浏览器都支持它:Firefox、Safari、Chrome、Opera和IE。

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

arguments.callee.toString();

似乎正符合你的需要。

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

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

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

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

你可以使用Function.name:

在大多数JavaScript实现中,一旦你在作用域中有了构造函数的引用,你就可以从它的name属性(例如Function.name,或Object.constructor.name)中获得它的字符串名称

你可以使用Function.callee:

原生论点。调用者方法已弃用,但大多数浏览器支持Function。调用者,它将返回实际调用对象(其代码体): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcaller

你可以创建一个源映射:

如果你需要的是字面函数签名(它的“名字”)而不是对象本身,你可能不得不求助于一些更定制的东西,比如创建一个你需要经常访问的API字符串值的数组引用。您可以使用Object.keys()和字符串数组将它们映射在一起

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