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

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

当前回答

试试Function.name吧

const func1 = function() {};

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

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

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

其他回答

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

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

你可以使用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()和字符串数组将它们映射在一起

在ES6中,你可以只使用myFunction.name。

注意:为了更好地压缩,一些JS的迷你器可能会丢弃函数名;你可能需要调整他们的设置来避免这种情况。

在ES5中,最好的做法是:

function functionName(fun) {
  var ret = fun.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}

使用函数。调用者是非标准的。函数。调用者和实参。在严格模式下,被调用都是被禁止的。

编辑:nus的基于正则表达式的答案实现了同样的事情,但有更好的性能!

任何构造函数都公开一个属性名,即函数名。你可以通过实例(使用new)或原型访问构造函数:

function Person() {
  console.log(this.constructor.name); //Person
}

var p = new Person();
console.log(p.constructor.name); //Person

console.log(Person.prototype.constructor.name);  //Person

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

看到stacktrace.js