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

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

其他回答

可以使用name属性获取函数名,除非使用匿名函数

例如:

var Person = function Person () {
  this.someMethod = function () {};
};

Person.prototype.getSomeMethodName = function () {
  return this.someMethod.name;
};

var p = new Person();
// will return "", because someMethod is assigned with anonymous function
console.log(p.getSomeMethodName());

现在让我们试试named function

var Person = function Person () {
  this.someMethod = function someMethod() {};
};

现在你可以使用

// will return "someMethod"
p.getSomeMethodName()

你不能。根据标准,函数没有名字(尽管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

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

{your_function}.prototype.constructor.name

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

这对我很管用。

function AbstractDomainClass() {
    this.className = function() {
        if (!this.$className) {
            var className = this.constructor.toString();
            className = className.substr('function '.length);
            className = className.substr(0, className.indexOf('('));
            this.$className = className;
        }
        return this.$className;
    }
}

测试代码:

var obj = new AbstractDomainClass();
expect(obj.className()).toBe('AbstractDomainClass');

任何构造函数都公开一个属性名,即函数名。你可以通过实例(使用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