如何从函数中获取函数名?

时间:2022-02-21 07:05:28

How can I access a function name from inside that function?

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

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

17 个解决方案

#1


137  

In ES5, the best thing to do is:

在ES5中,最好的做法是:

function functionName(fun) {
  var ret = fun.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}

Using Function.caller is non-standard. Function.caller and arguments.callee are both forbidden in strict mode.

使用函数。调用者是不标准的。函数。调用者和参数。callee在严格的模式下都是被禁止的。

Edit: nus's regex based answer below achieves the same thing, but has better performance!

编辑:以下是新加坡国立大学基于regex的回答,达到同样的效果,但有更好的表现!

In ES6, you can just use myFunction.name.

在ES6中,您可以使用myfunction。name。

Note: Beware that some JS minifiers might throw away function names, to compress better; you may need to tweak their settings to avoid that.

注意:要更好地压缩,要注意,一些JS小型程序可能会丢弃函数名;您可能需要调整它们的设置以避免这种情况。

#2


102  

ES6 (inspired by sendy halim's answer below):

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

myFunction.name

Explanation on MDN. As of 2015 works in nodejs and all major browsers except IE.

解释中数。截至2015年,nodejs和除IE外的所有主要浏览器均使用该软件。

Note: On bound functions this will give "bound <originalName>". You will have to strip the "bound " if you want to get the original name.

注意:在绑定函数上,这将给出“绑定 ”。如果你想要得到原来的名字,你必须去掉“界限”。


ES5 (inspired by Vlad's answer):

ES5(灵感来自弗拉德的回答):

If you have a reference to the function, you can do:

如果你有参考功能,你可以:

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
}
  • I have not run unit tests on this, or verified implementation differences, but in principle it should work, if not leave a comment.
  • 我没有在这个方面运行单元测试,或者验证了实现的差异,但是原则上它应该工作,如果没有留下评论的话。
  • Note: won't work on bound functions
  • 注意:在绑定函数上不能工作
  • Note: that caller and callee are considered deprecated.
  • 注意:调用者和被调用者被认为是不赞成的。

[1] I include it here because it is legal and often enough syntax highlighting tools fail to take into account the white space between function name and parenthesis. On the other hand, I'm not aware of any implementation of .toString() that will include white space here, so that's why you can omit it.

[1]之所以在这里包含它,是因为它是合法的,而且常常有足够多的语法突出显示工具没有考虑到函数名和括号之间的空白。另一方面,我没有意识到. tostring()的任何实现,其中将包含空格,所以您可以省略它。


As an answer to the original question, I would drop parasitic inheritance and go for some more traditional OOP design patterns. I wrote a TidBits.OoJs to comfortably write OOP code in JavaScript with a feature set mimicking C++ (not yet complete, but mostly).

作为对原始问题的回答,我将放弃寄生继承,而采用一些更传统的OOP设计模式。我写了一个花絮。OoJs可以轻松地用JavaScript编写OOP代码,并使用一个模拟c++的特性集(虽然还不完整,但主要是)。

I see from the comments that you would like to avoid passing information parent needs to it's constructor. I must admit that traditional design patterns won't save you from that one though, since it is generally a considered a good thing to make your dependencies obvious and enforced.

我从注释中看到,您希望避免将父类需要的信息传递给它的构造函数。我必须承认,传统的设计模式并不能将您从这个模式中拯救出来,因为让您的依赖关系变得明显和强制通常被认为是一件好事。

I would also suggest to steer away from anonymous functions. They only make debugging and profiling a PITA because everything just shows up as "anonymous function", and there is no benefit to them that I'm aware of.

我还建议不要使用匿名函数。它们只做调试和分析一个PITA,因为所有东西都显示为“匿名函数”,我知道它们没有任何好处。

#3


40  

what you're doing is assigning unnamed function to a variable. you probably need named function expression instead ( http://kangax.github.com/nfe/ ).

你要做的是给一个变量分配一个未命名的函数。您可能需要使用命名函数表达式(http://kangax.github.com/nfe/)。

var x = function x() {
    console.log( arguments.callee.name );
}
x();

however I'm not sure how much cross-browser that is; there's an issue with IE6 that makes you function's name leak to the outer scope. also, arguments.callee is kind of deprecated and will result in error if you're using strict mode.

但是我不确定有多少跨浏览器;IE6有一个问题,它使您的函数的名称泄漏到外部范围。同时,参数。callee是不赞成的,如果您使用严格模式,它会导致错误。

#4


14  

Any constructor exposes a property name, which is the function name. You access the constructor via an instance (using new) or a prototype:

任何构造函数都公开一个属性名,即函数名。通过实例(使用新的)或原型访问构造函数:

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

#5


12  

This might work for you:

这可能对你有用:

function foo() { bar(); }

function bar() { console.log(bar.caller.name); }

running foo() will output "foo" or undefined if you call from an anonymous function.

如果从匿名函数调用,运行foo()将输出“foo”或未定义的。

It works with constructors too, in which case it would output the name of the calling constructor (eg "Foo").

它也与构造函数一起工作,在这种情况下,它将输出调用构造函数的名称(如“Foo”)。

More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

更多信息:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

They claim it's non-standard, but also that it's supported by all major browsers: Firefox, Safari, Chrome, Opera and IE.

他们声称这是不标准的,但也支持所有主流浏览器:Firefox、Safari、Chrome、Opera和IE。

#6


8  

You can't. Functions don't have names according to the standard (though mozilla has such an attribute) - they can only be assigned to variables with names.

你不能。函数没有按照标准的名称(尽管mozilla有这样的属性)——它们只能分配给带有名称的变量。

Also your comment:

你的评论:

// access fully qualified name (ie "my.namespace.myFunc")

is inside the function my.namespace.myFunc.getFn

在函数mynamespace . myfunction . getfn中吗

What you can do is return the constructor of an object created by new

您可以做的是返回由new创建的对象的构造函数

So you could say

所以你可以说

var obj = new my.namespace.myFunc();
console.info(obj.constructor); //my.namespace.myFunc

#7


4  

You can use name property to get the function name, unless you're using an anonymous function

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

For example:

例如:

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

now let's try with named function

现在我们来试试命名函数

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

now you can use

现在你可以使用

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

#8


3  

You could use Function.name:

您可以使用Function.name:

In most implementations of JavaScript, once you have your constructor's reference in scope, you can get its string name from its name property (e.g. Function.name, or Object.constructor.name

在JavaScript的大多数实现中,一旦在作用域中有了构造函数的引用,就可以从它的name属性(例如Function.name或object . construction .name)获取它的字符串名

You could use Function.callee:

您可以使用Function.callee:

The native arguments.caller method has been deprecated, but most browsers support Function.caller, which will return the actual invoking object (its body of code): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcaller

本机参数。调用方方法已被废弃,但大多数浏览器都支持这个功能。调用者,它将返回实际调用对象(它的代码主体):https://developer.mozilla.org/en- us/docs/web/javascript/reference/global_objects/function/caller?

You could create a source map:

您可以创建一个源映射:

If what you need is the literal function signature (the "name" of it) and not the object itself, you might have to resort to something a little more customized, like creating an array reference of the API string values you'll need to access frequently. You can map them together using Object.keys() and your array of strings, or look into Mozilla's source maps library on GitHub, for bigger projects: https://github.com/mozilla/source-map

如果您需要的是字面函数签名(它的“名称”)而不是对象本身,那么您可能需要使用一些更定制的东西,比如创建一个API字符串值的数组引用,您将需要频繁访问这些值。您可以使用Object.keys()和字符串数组将它们映射到一起,或者在GitHub上查看Mozilla的源地图库,用于更大的项目:https://github.com/mozilla/source-map。

#9


2  

You could use this, but it's not for all browsers, only the ones that support Error.stack

您可以使用它,但它并不适用于所有浏览器,只适用于支持Error.stack的浏览器

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

Of course this is for the current function, but you get the idea.

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

Cheers!

干杯!

#10


2  

as part as ECMAScript 6 you can use Function.name method

作为ECMAScript 6的一部分,您可以使用Function.name方法。

function doSomething() {}

alert(doSomething.name); // alerts "doSomething"

#11


2  

It looks like the most stupid thing, that I wrote in my life, but it's funny :D

这看起来是我一生中最愚蠢的事情,但很好笑:D。

function getName(d){
  const error = new Error();
  const firefoxMatch = (error.stack.split('\n')[0 + d].match(/^.*(?=@)/) || [])[0];
  const chromeMatch = ((((error.stack.split('at ') || [])[1 + d] || '').match(/(^|\.| <| )(.*[^(<])( \()/) || [])[2] || '').split('.').pop();
  const safariMatch = error.stack.split('\n')[0 + d];

  // firefoxMatch ? console.log('firefoxMatch', firefoxMatch) : void 0;
  // chromeMatch ? console.log('chromeMatch', chromeMatch) : void 0;
  // safariMatch ? console.log('safariMatch', safariMatch) : void 0;

  return firefoxMatch || chromeMatch || safariMatch;
}

d - depth of stack. 0 - return this function name, 1 - parent, etc.;
[0 + d] - just for understanding - what happens;
firefoxMatch - works for safari, but I had really a little time for testing, because mac's owner had returned after smoking, and drove me away :'(

d -堆栈深度。0 -返回这个函数名,1 - parent等;[0 + d] -只是为了理解发生了什么;firefoxMatch -适用于safari浏览器,但我确实有一点时间进行测试,因为mac的主人吸烟后回来了,把我赶走了。

Testing:

测试:

function limbo(){
  for(let i = 0; i < 4; i++){
    console.log(getName(i));
  }
}
function lust(){
  limbo();
}
function gluttony(){
  lust();
}

gluttony();

Result:
Chrome:
如何从函数中获取函数名?

结果:铬:

Fitefox:
如何从函数中获取函数名?

Fitefox:

This solution was creating only just for fun! Dont use it for real projects. It not depends on ES specification, it depends only on browser realisation. After next chrome/firefox/safari update it may be broken.
More than that there is no error (ha) processing - if d will be more than stack length - you will get an error;
For other wrowsers error's messaage pattern - you will get an error;
It must work for ES6 classes (.split('.').pop()), but you sill can get an erorr;

这个解决方案只是为了好玩而已!不要把它用在真正的项目上。它不依赖于ES规范,它只依赖于浏览器的实现。在下一次chrome/firefox/safari更新后,它可能会被破坏。更重要的是,没有错误(ha)处理——如果d将超过堆栈长度——您将会得到一个错误;对于其他wrowsers错误的messaage模式——您将得到一个错误;它必须适用于ES6类(.split('. .pop())),但您仍然可以获得erorr;

#12


1  

look here: http://www.tek-tips.com/viewthread.cfm?qid=1209619

看这里:http://www.tek-tips.com/viewthread.cfm?qid=1209619

arguments.callee.toString();

seems to be right for your needs.

看来你的需要是正确的。

#13


1  

I know this is a old question but lately I've been facing some similar issue while trying to decorate some React Component's methods, for debugging purposes. As people already said, arguments.caller and arguments.callee are forbidden in strict mode which is probably enabled by default in your React transpiling. You can either disable it, or I've been able to come up with another hack, because in React all class functions are named, you can actually do this:

我知道这是一个老问题,但最近我在尝试修饰某个React组件的方法时遇到了类似的问题,以便调试。正如人们已经说过的,争论。调用者和参数。在严格的模式下,callee是被禁止的,这在你的反应中是默认的。你可以禁用它,或者我可以想出另一个hack,因为在反应所有的类函数时,你可以这样做:

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

#14


0  

This worked for me.

这为我工作。

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;
    }
}

Test code:

测试代码:

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

#15


0  

I had a similar problem and I solved it as follows:

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

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

This code implements, in a more comfortable fashion, one response I already read here at the top of this discussion. Now I have a member function retrieving the name of any function object. Here's the full script ...

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

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

#16


0  

you can use Error.stack to trace the function name and exact position of where you are in it.

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

See stacktrace.js

看到stacktrace.js

#17


-2  

Easy way to get function name from within fuction you are running.

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

function x(){alert(this.name)};x()

#1


137  

In ES5, the best thing to do is:

在ES5中,最好的做法是:

function functionName(fun) {
  var ret = fun.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}

Using Function.caller is non-standard. Function.caller and arguments.callee are both forbidden in strict mode.

使用函数。调用者是不标准的。函数。调用者和参数。callee在严格的模式下都是被禁止的。

Edit: nus's regex based answer below achieves the same thing, but has better performance!

编辑:以下是新加坡国立大学基于regex的回答,达到同样的效果,但有更好的表现!

In ES6, you can just use myFunction.name.

在ES6中,您可以使用myfunction。name。

Note: Beware that some JS minifiers might throw away function names, to compress better; you may need to tweak their settings to avoid that.

注意:要更好地压缩,要注意,一些JS小型程序可能会丢弃函数名;您可能需要调整它们的设置以避免这种情况。

#2


102  

ES6 (inspired by sendy halim's answer below):

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

myFunction.name

Explanation on MDN. As of 2015 works in nodejs and all major browsers except IE.

解释中数。截至2015年,nodejs和除IE外的所有主要浏览器均使用该软件。

Note: On bound functions this will give "bound <originalName>". You will have to strip the "bound " if you want to get the original name.

注意:在绑定函数上,这将给出“绑定 ”。如果你想要得到原来的名字,你必须去掉“界限”。


ES5 (inspired by Vlad's answer):

ES5(灵感来自弗拉德的回答):

If you have a reference to the function, you can do:

如果你有参考功能,你可以:

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
}
  • I have not run unit tests on this, or verified implementation differences, but in principle it should work, if not leave a comment.
  • 我没有在这个方面运行单元测试,或者验证了实现的差异,但是原则上它应该工作,如果没有留下评论的话。
  • Note: won't work on bound functions
  • 注意:在绑定函数上不能工作
  • Note: that caller and callee are considered deprecated.
  • 注意:调用者和被调用者被认为是不赞成的。

[1] I include it here because it is legal and often enough syntax highlighting tools fail to take into account the white space between function name and parenthesis. On the other hand, I'm not aware of any implementation of .toString() that will include white space here, so that's why you can omit it.

[1]之所以在这里包含它,是因为它是合法的,而且常常有足够多的语法突出显示工具没有考虑到函数名和括号之间的空白。另一方面,我没有意识到. tostring()的任何实现,其中将包含空格,所以您可以省略它。


As an answer to the original question, I would drop parasitic inheritance and go for some more traditional OOP design patterns. I wrote a TidBits.OoJs to comfortably write OOP code in JavaScript with a feature set mimicking C++ (not yet complete, but mostly).

作为对原始问题的回答,我将放弃寄生继承,而采用一些更传统的OOP设计模式。我写了一个花絮。OoJs可以轻松地用JavaScript编写OOP代码,并使用一个模拟c++的特性集(虽然还不完整,但主要是)。

I see from the comments that you would like to avoid passing information parent needs to it's constructor. I must admit that traditional design patterns won't save you from that one though, since it is generally a considered a good thing to make your dependencies obvious and enforced.

我从注释中看到,您希望避免将父类需要的信息传递给它的构造函数。我必须承认,传统的设计模式并不能将您从这个模式中拯救出来,因为让您的依赖关系变得明显和强制通常被认为是一件好事。

I would also suggest to steer away from anonymous functions. They only make debugging and profiling a PITA because everything just shows up as "anonymous function", and there is no benefit to them that I'm aware of.

我还建议不要使用匿名函数。它们只做调试和分析一个PITA,因为所有东西都显示为“匿名函数”,我知道它们没有任何好处。

#3


40  

what you're doing is assigning unnamed function to a variable. you probably need named function expression instead ( http://kangax.github.com/nfe/ ).

你要做的是给一个变量分配一个未命名的函数。您可能需要使用命名函数表达式(http://kangax.github.com/nfe/)。

var x = function x() {
    console.log( arguments.callee.name );
}
x();

however I'm not sure how much cross-browser that is; there's an issue with IE6 that makes you function's name leak to the outer scope. also, arguments.callee is kind of deprecated and will result in error if you're using strict mode.

但是我不确定有多少跨浏览器;IE6有一个问题,它使您的函数的名称泄漏到外部范围。同时,参数。callee是不赞成的,如果您使用严格模式,它会导致错误。

#4


14  

Any constructor exposes a property name, which is the function name. You access the constructor via an instance (using new) or a prototype:

任何构造函数都公开一个属性名,即函数名。通过实例(使用新的)或原型访问构造函数:

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

#5


12  

This might work for you:

这可能对你有用:

function foo() { bar(); }

function bar() { console.log(bar.caller.name); }

running foo() will output "foo" or undefined if you call from an anonymous function.

如果从匿名函数调用,运行foo()将输出“foo”或未定义的。

It works with constructors too, in which case it would output the name of the calling constructor (eg "Foo").

它也与构造函数一起工作,在这种情况下,它将输出调用构造函数的名称(如“Foo”)。

More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

更多信息:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

They claim it's non-standard, but also that it's supported by all major browsers: Firefox, Safari, Chrome, Opera and IE.

他们声称这是不标准的,但也支持所有主流浏览器:Firefox、Safari、Chrome、Opera和IE。

#6


8  

You can't. Functions don't have names according to the standard (though mozilla has such an attribute) - they can only be assigned to variables with names.

你不能。函数没有按照标准的名称(尽管mozilla有这样的属性)——它们只能分配给带有名称的变量。

Also your comment:

你的评论:

// access fully qualified name (ie "my.namespace.myFunc")

is inside the function my.namespace.myFunc.getFn

在函数mynamespace . myfunction . getfn中吗

What you can do is return the constructor of an object created by new

您可以做的是返回由new创建的对象的构造函数

So you could say

所以你可以说

var obj = new my.namespace.myFunc();
console.info(obj.constructor); //my.namespace.myFunc

#7


4  

You can use name property to get the function name, unless you're using an anonymous function

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

For example:

例如:

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

now let's try with named function

现在我们来试试命名函数

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

now you can use

现在你可以使用

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

#8


3  

You could use Function.name:

您可以使用Function.name:

In most implementations of JavaScript, once you have your constructor's reference in scope, you can get its string name from its name property (e.g. Function.name, or Object.constructor.name

在JavaScript的大多数实现中,一旦在作用域中有了构造函数的引用,就可以从它的name属性(例如Function.name或object . construction .name)获取它的字符串名

You could use Function.callee:

您可以使用Function.callee:

The native arguments.caller method has been deprecated, but most browsers support Function.caller, which will return the actual invoking object (its body of code): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcaller

本机参数。调用方方法已被废弃,但大多数浏览器都支持这个功能。调用者,它将返回实际调用对象(它的代码主体):https://developer.mozilla.org/en- us/docs/web/javascript/reference/global_objects/function/caller?

You could create a source map:

您可以创建一个源映射:

If what you need is the literal function signature (the "name" of it) and not the object itself, you might have to resort to something a little more customized, like creating an array reference of the API string values you'll need to access frequently. You can map them together using Object.keys() and your array of strings, or look into Mozilla's source maps library on GitHub, for bigger projects: https://github.com/mozilla/source-map

如果您需要的是字面函数签名(它的“名称”)而不是对象本身,那么您可能需要使用一些更定制的东西,比如创建一个API字符串值的数组引用,您将需要频繁访问这些值。您可以使用Object.keys()和字符串数组将它们映射到一起,或者在GitHub上查看Mozilla的源地图库,用于更大的项目:https://github.com/mozilla/source-map。

#9


2  

You could use this, but it's not for all browsers, only the ones that support Error.stack

您可以使用它,但它并不适用于所有浏览器,只适用于支持Error.stack的浏览器

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

Of course this is for the current function, but you get the idea.

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

Cheers!

干杯!

#10


2  

as part as ECMAScript 6 you can use Function.name method

作为ECMAScript 6的一部分,您可以使用Function.name方法。

function doSomething() {}

alert(doSomething.name); // alerts "doSomething"

#11


2  

It looks like the most stupid thing, that I wrote in my life, but it's funny :D

这看起来是我一生中最愚蠢的事情,但很好笑:D。

function getName(d){
  const error = new Error();
  const firefoxMatch = (error.stack.split('\n')[0 + d].match(/^.*(?=@)/) || [])[0];
  const chromeMatch = ((((error.stack.split('at ') || [])[1 + d] || '').match(/(^|\.| <| )(.*[^(<])( \()/) || [])[2] || '').split('.').pop();
  const safariMatch = error.stack.split('\n')[0 + d];

  // firefoxMatch ? console.log('firefoxMatch', firefoxMatch) : void 0;
  // chromeMatch ? console.log('chromeMatch', chromeMatch) : void 0;
  // safariMatch ? console.log('safariMatch', safariMatch) : void 0;

  return firefoxMatch || chromeMatch || safariMatch;
}

d - depth of stack. 0 - return this function name, 1 - parent, etc.;
[0 + d] - just for understanding - what happens;
firefoxMatch - works for safari, but I had really a little time for testing, because mac's owner had returned after smoking, and drove me away :'(

d -堆栈深度。0 -返回这个函数名,1 - parent等;[0 + d] -只是为了理解发生了什么;firefoxMatch -适用于safari浏览器,但我确实有一点时间进行测试,因为mac的主人吸烟后回来了,把我赶走了。

Testing:

测试:

function limbo(){
  for(let i = 0; i < 4; i++){
    console.log(getName(i));
  }
}
function lust(){
  limbo();
}
function gluttony(){
  lust();
}

gluttony();

Result:
Chrome:
如何从函数中获取函数名?

结果:铬:

Fitefox:
如何从函数中获取函数名?

Fitefox:

This solution was creating only just for fun! Dont use it for real projects. It not depends on ES specification, it depends only on browser realisation. After next chrome/firefox/safari update it may be broken.
More than that there is no error (ha) processing - if d will be more than stack length - you will get an error;
For other wrowsers error's messaage pattern - you will get an error;
It must work for ES6 classes (.split('.').pop()), but you sill can get an erorr;

这个解决方案只是为了好玩而已!不要把它用在真正的项目上。它不依赖于ES规范,它只依赖于浏览器的实现。在下一次chrome/firefox/safari更新后,它可能会被破坏。更重要的是,没有错误(ha)处理——如果d将超过堆栈长度——您将会得到一个错误;对于其他wrowsers错误的messaage模式——您将得到一个错误;它必须适用于ES6类(.split('. .pop())),但您仍然可以获得erorr;

#12


1  

look here: http://www.tek-tips.com/viewthread.cfm?qid=1209619

看这里:http://www.tek-tips.com/viewthread.cfm?qid=1209619

arguments.callee.toString();

seems to be right for your needs.

看来你的需要是正确的。

#13


1  

I know this is a old question but lately I've been facing some similar issue while trying to decorate some React Component's methods, for debugging purposes. As people already said, arguments.caller and arguments.callee are forbidden in strict mode which is probably enabled by default in your React transpiling. You can either disable it, or I've been able to come up with another hack, because in React all class functions are named, you can actually do this:

我知道这是一个老问题,但最近我在尝试修饰某个React组件的方法时遇到了类似的问题,以便调试。正如人们已经说过的,争论。调用者和参数。在严格的模式下,callee是被禁止的,这在你的反应中是默认的。你可以禁用它,或者我可以想出另一个hack,因为在反应所有的类函数时,你可以这样做:

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

#14


0  

This worked for me.

这为我工作。

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;
    }
}

Test code:

测试代码:

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

#15


0  

I had a similar problem and I solved it as follows:

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

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

This code implements, in a more comfortable fashion, one response I already read here at the top of this discussion. Now I have a member function retrieving the name of any function object. Here's the full script ...

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

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

#16


0  

you can use Error.stack to trace the function name and exact position of where you are in it.

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

See stacktrace.js

看到stacktrace.js

#17


-2  

Easy way to get function name from within fuction you are running.

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

function x(){alert(this.name)};x()