Javascript函数调用不可用

Javascript call to function not available

本文关键字:函数调用 Javascript      更新时间:2023-09-26

我有一个脚本javascript的问题。在某个函数和变量中有一个对象。在这些函数之一,我使ajax请求和错误处理程序内,我调用在同一对象中定义的函数,但调试器说,该函数是"不可用",但在对象中定义的变量是可见的…

这是Javascript中包含对象的部分:

Utils = {
"defaultErrorMessage" : "Ci scusiamo per il disagio ma qualcosa è andato storto, probabilmente è una cosa temporanea, ritenta in un altro momento",
"base_url" : $('#base_url').val(),
getApiUri : function(name) {
    return window.location.protocol + "//" + window.location.host + PATH[ENV] + name + ENV == 'stub' ? '.json' : '';
},
callServer : function(uri, data, successCallback) {
    $.ajax({
        type: "POST",
        url: this.base_url + "index.php/" + uri,
        data: data,
        dataType: "json",
        cache: false,
        beforeSend: function(XMLHttpRequest)
        {
            waitingDialog.show('Caricamento...');
        },
        success:
            function (data) {
                //alert(data);  //as a debugging message.
                successCallback(data);
            },
        error: function (xhr, ajaxOptions, thrownError) {
            //alert("Qualcosa di storto: "+ xhr.status + " messaggio: " + xhr.responseText);
            this.showModalDialog('error','Siamo spiacenti :(', this.defaultErrorMessage);
        },
        complete: function() {
            waitingDialog.hide();
        }
    });
},
hideAllMessages: function ()
{
    var messagesHeights = new Array(); // this array will store height for each
    for (i=0; i<myMessages.length; i++)
    {
        messagesHeights[i] = $('.' + myMessages[i]).outerHeight();
        $('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
    }
},
showMessage: function(type, title, message) {
    var title = (typeof title !== 'undefined') ? title : '';
    var message = (typeof message !== 'undefined') ? message : '';
    this.hideAllMessages();
    if (title != '')
        $('.'+type + ' h3').html(title);
    if (message != '')
        $('.'+type + ' p').html(message);
    $('.'+type).animate({top:"0"}, 500);
},
showModalDialog: function(type, title, message, withOK) {
    var withOK = (typeof withOK !== 'undefined') ? withOK : false;
    $div = $('<div id="error" title="'+title+'">');
    $div.append('<p>'+message+'</p>');
    if (!withOK) {
        $div.dialog({
            modal: true,
            maxHeight: 500
        }).prev(".ui-dialog-titlebar").css("background", colorDialog[type]);
    }
    else {
        $div.dialog({
            modal: true,
            maxHeight: 500,
            buttons: {
                Ok: function() {
                    $( this ).dialog( "close" );
                }
            }
        }).prev(".ui-dialog-titlebar").css("background", colorDialog[type]);
    }
},
validateEmail: function(email) {
    var re = /^(([^<>()'[']''.,;:'s@"]+('.[^<>()'[']''.,;:'s@"]+)*)|(".+"))@(('[[0-9]{1,3}'.[0-9]{1,3}'.[0-9]{1,3}'.[0-9]{1,3}])|(([a-zA-Z'-0-9]+'.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

};

<为什么strong>。showModalDialog在错误处理程序中不可用?我也试过没有"this",但也是一样的…

this并不总是在回调函数中工作,因为上下文发生了变化,所以this指的是不再是您的Utils对象的东西。解决这个问题的方法是保留一个变量,以便在需要时记住上下文是什么。在callServer函数中,在ajax调用之前,添加var self = this。然后当你需要引用showModalDialog时,你可以用self.showModalDialog();

来调用它
callServer : function(uri, data, successCallback) {
     var self = this;
     $.ajax({
       ...
          self.showModalDialog();

问题是this代表您在callServer中的对象,但它在传递给Ajax调用的函数中没有相同的含义,而是代表您传递给$.ajax()作为参数的对象。

您需要将其作为另一个变量传递,如self

Inside callServer

var self = this;

错误处理程序内部

self.showModalDialog();