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

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

当前回答

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

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

其他回答

这对我很管用。

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');

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

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

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

看到stacktrace.js

可以使用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()

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

{your_function}.prototype.constructor.name

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