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

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

其他回答

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

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

{your_function}.prototype.constructor.name

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

试试Function.name吧

const func1 = function() {};

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

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

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

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

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

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

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

ES6(灵感来自sendy halim的回答):

myFunction.name

MDN说明。截至2015年,可以在nodejs和除IE之外的所有主流浏览器上运行。

注意:对于绑定函数,这将给出"bound <originalName>"。如果你想要得到原来的名字,你必须去掉“束缚”。


ES5(灵感来自Vlad的回答):

如果你有一个函数的引用,你可以这样做:

function functionName( func )
{
    // Match:
    // - ^          the beginning of the string
    // - function   the word 'function'
    // - \s+        at least some white space
    // - ([\w\$]+)  capture one or more valid JavaScript identifier characters
    // - \s*        optionally followed by white space (in theory there won't be any here,
    //              so if performance is an issue this can be omitted[1]
    // - \(         followed by an opening brace
    //
    var result = /^function\s+([\w\$]+)\s*\(/.exec( func.toString() )

    return  result  ?  result[ 1 ]  :  '' // for an anonymous function there won't be a match
}

我没有对此运行单元测试,也没有对实现进行验证 分歧,但原则上应该工作,如果没有留下评论。 注意:不适用于绑定函数 注意:调用者和被调用者被认为已弃用。

我把它放在这里是因为它是合法的,而且经常有足够的语法高亮显示工具没有考虑到函数名和圆括号之间的空白。另一方面,我不知道. tostring()的任何实现会在这里包含空白,所以这就是为什么你可以省略它。


作为对最初问题的回答,我会放弃寄生继承,转而采用一些更传统的OOP设计模式。我写了一篇花絮。OoJs可以轻松地用JavaScript编写OOP代码,并带有模仿c++的特性集(还没有完成,但大部分是)。

我从评论中看到,你想避免传递信息的父需要它的构造函数。我必须承认,传统的设计模式并不能使您摆脱这种情况,因为使您的依赖关系明显和强制通常被认为是一件好事。

我还建议避免使用匿名函数。他们只对PITA进行调试和分析,因为一切都显示为“匿名函数”,据我所知,这对他们没有任何好处。