lmcDevloper
lmcDevloper

Reputation: 332

jQuery + access to the name of the function

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?

Upvotes: 1

Views: 43

Answers (3)

programndial
programndial

Reputation: 167

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.

Upvotes: 0

dfsq
dfsq

Reputation: 193311

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.

Upvotes: 1

Uzbekjon
Uzbekjon

Reputation: 11823

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).

Upvotes: 0

Related Questions