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

// 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.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>

其他回答

这可能对你有用:

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。

在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的基于正则表达式的答案实现了同样的事情,但有更好的性能!

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

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

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

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

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

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

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

看到stacktrace.js