get name of attribute function executing in class

While developing a way to detect which was the method of a class that was being executed, it occurred to me to use the name of this one. searching through various forums I found that apparently there is no way, It not exists using the structure I gave as an example, but it can be done by other functions or classes inside this class. I wanted to ask if there is a way as I only found & but it throws an error.

Sorry if this forum is not for this, but I found the question very specific to make ask in other forums.
what I'm really looking for is to get myFunction1 here my code example

class myClass {

    myFunction1 = function(){

        console.log( // return error

    myFunction2 = function(){

        console.log(this) // return undefined

new myClass().myFunction1() // return error, but i need myFunction1

I know it's really as simple as setting the name of the function in a variable, but it's really because I'm looking to do something more generic.

I hope you can help me, I would be very grateful

If you use the function keyword, (like in your example) you can give an explicit name to the function, and get the reference to the function you are executing using that name.

    myFunction1 = function bar() {

(Here, Iā€™m using bar in order to distinguish it from the myFunction1 variable or property but of course, you will probably want to use myFunction1.)

It works but this solution is equivalent to entering the name of the function in a variable, since I am necessarily entering the name of the variable on this occasion 3 times.

I don't believe there is any way to get "the name of the current function" without hardcoding something. However, it's very unclear why you'd need this, since you'd have to copy-paste such a keyword into each function, in which case you could use a named function and explicitly use the name in each one.


You could do some stack trace hacking to get it:

let secondLine
try {
  throw new Error()
} catch (e) {
  // First line is the error name, second the immediate callee
  [, secondLine] = /^[^\n]+\n([^\n]+)\n/.exec(e.stack)
// And now parse out the line for the error. Note: this differs across
// browsers.

But in general, why do you need this?

1 Like

woah perfect is exactly what i was looking for.

It is for log issues, I needed to know exactly what class and what method was being invoked when the error occurred. Before we left a string (and sometimes we forgot to change it) but with this it will be much more comfortable and avoid errors

thank you very much really. you are geniuses