Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

javascript - Get function name from inside itself

let's say I have a function:

 function test1() {

       }

I want to return "test1" from within itself. I found out that you can do arguments.callee which is going to return the whole function and then do some ugly regex. Any better way?

what about namespaced functions?

is it possible to get their name as well: e.g.:

var test2 = 
{
 foo: function() {
    }
};

I want to return foo for this example from within itself.

update: for arguments.callee.name Chrome returns blank, IE9 returns undefined. and it does not work with scoped functions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var test2 = {
   foo: function() {
   }
};

You aren't giving the function a name. You are assigning the foo property of test2 to an anonymous function.

arguments.callee.name only works when functions are declared using the function foo(){} syntax.

This should work:

var test2 = {
   foo: function foo() {
      console.log(arguments.callee.name); // "foo"
   }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...