最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get anonymous function name - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 6, 2013 at 1:16 Adam HalaszAdam Halasz 58.3k67 gold badges153 silver badges216 bronze badges 2
  • 1 well there is no way to do this, can you describe what problem do you want to solve ? – kirugan Commented Jan 6, 2013 at 1:19
  • @kirugan, Reflection. – Pacerier Commented Feb 22, 2017 at 13:33
Add a comment  | 

4 Answers 4

Reset to default 11

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'

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.

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.

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];
发布评论

评论列表(0)

  1. 暂无评论