在javascript中获取当前函数名称

Mat*_*epa 16 jquery function

我有这段代码:

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
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

我想要的是de error scoope里面的警告显示了函数名,在本例中是"MyFunction",而是我得到的是错误:function.

我怎样才能做到这一点?

MD *_*med 18

这个 -

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
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

是你需要的.

arguments内部error功能是指这个方法本身的arguments对象.它没有引用MyFunction的arguments对象.这就是你得到的原因error:MyFunction.在这种情况下使用全局变量为您提供了解决此问题的方法.

另外,要获取函数的名称,您需要使用arguments.callee.name.arguments.callee将为您提供对调用函数的引用,而不是字符串中的函数名称.


Var*_*ant 6

arguments.callee.name但是在你的情况下,你想要的是上下文中的函数,不再MyFunction是声明为错误处理程序的匿名方法...