lmcDevloper lmcDevloper - 6 months ago 12
Javascript Question

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?

Answer

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.

Comments