Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 855
Matías Cánepa Avatar asked Jul 05 '11 18:07

Matías Cánepa


1 Answers

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.

like image 55
MD Sayem Ahmed Avatar answered Oct 04 '22 15:10

MD Sayem Ahmed