Matías Cánepa
Matías Cánepa

Reputation: 5974

get the current function name in javascript

I have this piece of code:

function MyFunction()
{
    $.ajax({
        type: "POST",
        url: "ajax.php",
        dataType: "json",
        data: "foo=bar",
        error:function(XMLHttpRequest, textStatus, errorThrown)
        {
            alert(arguments.callee);
        },
        success: function(jsonObject)
        {
            //do something
        }
    });
}

what I want is that the alert inside de error scoope shows the function name, in this case "MyFunction" but instead what I get is the error:function.

How can I achieve this?

Upvotes: 17

Views: 17112

Answers (7)

Halayem Anis
Halayem Anis

Reputation: 7805

Time to refresh this thread by a fresh answer :)

Use console.trace();

Just call console.trace() and Firebug will write a very informative stack trace to the console. Not only will it tell you which functions are on the stack, but it will include the value of each argument that was passed to each function. You can click the functions or objects to inspect them further.

JavaScript Example :

function fn1(arg1, arg2) {
    var arg3 = 'myArg3';
    fn2(arg1, arg2, arg3);
}
function fn2(arg1, arg2, arg3) {
    var obj = {
        attr1 : 'val1',
        attr2 : 'val2'
    };
    console.trace(obj);
}
fn1('myArg1', 'myArg2', 'myArg3');


Firefox console (version: 43.0.1) :

Firefox console (version: 43.0.1)


Google Chrome console (version: 47.0.2526.106 m):

Google Chrome console (version: 47.0.2526.106 m)

You can find here all of logging functions that you need

HTH

Upvotes: 4

wolfstevent
wolfstevent

Reputation: 685

In strict mode you can no longer reference callee (see the related discussion at Javascript: is the arguments array deprecated?) , so the answer from @Sayem is only valid if you aren't using strict mode. In general you want to invoke strict mode because of its benefits to your code's reliability (see @JohnResig article).

I still would like to have a way to reference the name of the current function just for the purposes of throw error messages with a context. E.g.

throw myFunctionName() + ': invalid number of arguments';

For now I have to hard-code the function name within the throws. I've moved code around and forgotten to update the hard-coded function names.

I've thought about a coding convention of having a THIS_FUNCTION_NAME = 'foobar' as a const defined at the head of the function, but of course that can get moved and not updated as well.

I guess as long as you have a stack trace available from the throw the point is moot.

Upvotes: 4

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29176

This -

var my_arguments;

function MyFunction() {
    my_arguments = arguments;

    $.ajax({
        type: "POST",
        url: "http://www.google.com",
        dataType: "json",
        data: "foo=bar",
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            alert(my_arguments.callee.name);
        },
        success: function(jsonObject) {
            //do something
        }
    });
}

is what you need.

The arguments inside the error function refers to this method's own arguments object. It does not refer to the MyFunction's arguments object. That's why you are getting error:MyFunction. Using a global variable in this case provides you a workaround to this problem.

Also, to get only the name of the function, you need to use arguments.callee.name. arguments.callee will give you a reference to the calling function, not a function name in string.

Upvotes: 18

davin
davin

Reputation: 45555

alert('MyFunction');

You can't do better than reliably, since that function has almost nothing to do with the error handler: The error handler can very possibly have been created in another context entirely, one enclosing MyFunction, or passed into it etc.

MyFunction doesn't call the handler so querying arguments.* isn't going to help.

You could inject a value into scope:

function MyFunction(){
   var _injectedFunctionName = arguments.callee.name;

   ...
   // inside the error handler
   alert(_injectedFunctionName);
   ...
}

Although that assumes that no value with the same name will collide (a reasonable assumption in many cases, and not so reasonable in others).

The fact that you want the function name is probably a good indication that you're thinking about the problem incorrectly. Maybe if you explain what you're trying to do more broadly the community can propose alternatives.

Upvotes: -2

Mfoo
Mfoo

Reputation: 3775

Try

            error:function(xhr){
              alert('Error: '+xhr.status+' '+xhr.statusText);
            }

Upvotes: -2

Variant
Variant

Reputation: 17385

What you want is arguments.callee.name however in your case the function in context in no longer MyFunction but the anonymous method declared as the error handler...

Upvotes: 6

kcbanner
kcbanner

Reputation: 4078

You are using arguments inside the scope of the error function. You need something like this if you want the arguments of MyFunction():

function MyFunction()
{
    var myfunction_arguments = arguments;

    $.ajax({
        type: "POST",
        url: "ajax.php",
        dataType: "json",
        data: "foo=bar",
        error:function(XMLHttpRequest, textStatus, errorThrown)
        {
            alert(myfunction_arguments.callee);
        },
        success: function(jsonObject)
        {
            //do something
        }
    });
}

Is that what you mean?


Upvotes: 1

Related Questions