0

I want to get current method name directly from this method body, my code which does not work is:

var myFunction = function(){
    console.log(arguments.callee.name); // output must be "myFunction" 
}


This works excellently

function myFunction() {
    console.log(arguments.callee.name); // output is "myFunction" 
}

what do you suggest me, is there any way to make this work? I searched for google more and more but did not find smth. helpful

Arkadi
  • 1,153
  • 1
  • 14
  • 35
  • 7
    It's an anoymous function, how can have a name? – adricadar Mar 19 '15 at 13:55
  • @adricadar is absolutely right. It simply has no name. You can, however, work around this by simply giving it one. See http://stackoverflow.com/questions/14178305/get-anonymous-function-name for how to do this and what implications it has (especially IE). – maryisdead Mar 19 '15 at 13:59
  • okay, is there any way to get variable name which value is this anonymous function? in the case "myFunction" – Arkadi Mar 19 '15 at 14:03

2 Answers2

2

The function is anonymous, has no name.

To get the variable name, follow this answer.

Solution 1: Try to create an object that has a property and you iterate through properties and display the name of the property.

var x = {
    myFunction : function(){      
    }
};

for(var variable in x)
{
    console.log(variable);
}

Solution 2: I tried to make an workaround. I consider that the property is the first from the object and i try do display the name of the property.

var funcTest = function() {   
    for(var variable in this) {
        console.log(variable);
        break;
    }
} 

var x = {  myFunction : funcTest  };
x.myFunction(); // myFunction

var y = { secondFunction : funcTest }
y.secondFunction(); // secondFunction
Community
  • 1
  • 1
adricadar
  • 9,971
  • 5
  • 33
  • 46
0

The solution was to give a name to the function:

var myMethod = function myMethod () {    
    console.log(arguments.callee.name); // output is "myMethod"
};

I don't like this way at all but it works in concrete task

adricadar
  • 9,971
  • 5
  • 33
  • 46
Arkadi
  • 1,153
  • 1
  • 14
  • 35