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

// 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 parent() {
    console.log(a.name);
  }; let a = parent
}
{
  function child() {
    console.log(a.name)
  }; let a = child
};

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

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

其他回答

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

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

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

我也遇到过类似的问题,解决方法如下:

Function.prototype.myname = function() {
   return this.toString()
       .substr( 0, this.toString().indexOf( "(" ) )
       .replace( "function ", "" ); 
}

这段代码以一种更舒适的方式实现了我已经在讨论的开头读到的一个响应。 现在我有一个成员函数检索任何函数对象的名称。 这是完整的剧本……

<script language="javascript" TYPE="text/javascript">

    Function.prototype.myname = function() { 
        return this.toString()
            .substr( 0, this.toString().indexOf( "(" ) )
            .replace("function ", "" ); 
    }
    function call_this( _fn ) { document.write( _fn.myname() ); }
    function _yeaaahhh() { /* do something */ }
    call_this( _yeaaahhh ); 

</script>

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

看到stacktrace.js

对于支持Error的浏览器,可以使用这个选项。堆栈(可能不是全部)

function WriteSomeShitOut(){ 
  var a = new Error().stack.match(/at (.*?) /);
  console.log(a[1]);
} 
WriteSomeShitOut();

当然这是针对当前函数的,但你懂的。

在你编程的时候开心地流口水