Get function name from inside

let's say I have a function:

function test1() { } 

I want to return "test1" from the inside. I found out that you can make arguments.callee which will return the whole function and then make some ugly regex. Any better way?

what about functions with names?

You can also get your name: for example :.

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

I want to return foo for this example from the inside.

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

+6
source share
1 answer
 var test2 = { foo: function() { } }; 

You do not give the function a name. You assign the foo test2 property to an anonymous function.

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

This should work:

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

Source: https://habr.com/ru/post/909226/


All Articles