1

I now is a silly question but is this, I can give the name of the current function? I am really interested in this because I usually use the console and i want to get it

var debug = true;
var myFunction = $( "div" ).on( "click", function(e) {
    //
    var error = "";
    var something = true;
    //
    if(something == true) error = "Something has happened"; 
    if(debug)
        console.log("Ups!" + myFunction.name + " >> "+ error);
    //
});

Thanks in advance

This doesn't work in my jQuery example

Can I get the name of the currently running function in JavaScript?

Community
  • 1
  • 1
lmcDevloper
  • 332
  • 2
  • 8

3 Answers3

1

You will need to use a named function instead of anonymous, i.e. give it a name:

$( "div" ).on( "click", function myFunction(e) {
    console.log("Ups!" + myFunction.name);
});

Also, you need to understand that with the code

var something = $("div").on("click", function() {})

something will be an instance of jQuery, not a callback function of course. So once again: use named function.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0
arguments.callee.toString();

will get you the entire callee line of code (i.e. function MyFunction()) then just substring it out from there.

Update for your exact situation, try

(function() {console.log("Ups!" + arguments.callee.toString() + " error");})();

sometimes declaring the action as an inline function makes things tick a little better.

programndial
  • 157
  • 9
0

You can get the function name using arguments.callee or arguments.callee.name.

  • arguments.callee returns the name with a brackets (myFunction()).
  • arguments.callee.name returns the name without those brackets (myFunction).
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54