Get anonymous function name

时间秒杀一切 提交于 2019-12-17 16:49:40

问题


How to get the the variable name from within a function in this example:

// it should return A
var A = function(){ console.log(this.name); } 

Is there something like this?


回答1:


That function is anonymous; it has no name. You could, however, give it a name:

var A = function a() {};

Then its name is accessible via Function.name:

var A = function a() {};
A.name
> 'a'



回答2:


I know this is an old thread, but still in search results. so just for reference:

a solution could simply be using the stacktrace.

var stack = new Error().stack;

use trim and split to get to the desired values.




回答3:


No, there is nothing like that in Javascript. That function is anonymous, so it has no name, and what you want is ambiguous because the function could just as easily have any number of variables referencing it like:

var a, b, c, d;
a = b = function(){ console.log(this.name); };
c = b;
d = c;
a = b = 5;
// a and b no longer refer to the function, but c and d both do

What is it you are actually trying to accomplish? I'm sure there is another way to achieve it.




回答4:


It is possible in recent versions of Chrome and Firefox as follows. I only recommend this for debugging purposes (e.g. javascript tracing in non-production)

var myNameInChrome = /.*Object\.(.*)\s\(/.exec(new Error().stack)[0];
var myNameInFF = new Error().stack.split("@")[0];


来源:https://stackoverflow.com/questions/14178305/get-anonymous-function-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!