简体   繁体   中英

how to get js method name from inside the method

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM