内部的jquery函数混淆了这个关键字

时间:2013-10-12 01:09:19

标签: javascript jquery class this

function chat() {
    this.waittime = 6000;
    this.intUpdate = null;

    this.sendChatUpdate = function (msg) {
        var Chatmsg = '0';
        if (msg > 0) {
            Chatmsg = $('#chatmsg');
            var m = Chatmsg.val();
            Chatmsg.val('');
        }

        var s = $("#chatnick").val();
        var r = $("#chatto").val();

        $.ajax({
            type: 'POST',
            url: 'Chat/ajax/Chat.php',
            data: {
                S: s,
                R: r,
                M: m
            },
            success: function (data) {
                this.ProcessChatReturn(data);
            },
            error: function (data) {
                this.ProcessChatReturn(data);
            }
        });
    }

    this.getUnreadChat = function (mr) {
        var s = $("#chatnick").val();
        $.ajax({
            type: 'POST',
            url: 'Chat/ajax/Chat.php',
            data: {
                S: s,
                UR: 1,
                MR: mr
            },
            success: function (data) {
                this.ProcessChatReturn(data);
            },
            error: function (data) {
                this.ProcessChatReturn(data);
            }
        });

        //clearTimeout(intUpdate);
        $('#chatbox').show();
    }
}

var chat = new chat();
chat.getUnreadChat();

我收到错误“Uncaught TypeError:Object#没有方法'ProcessChatReturn'”

我认为这是因为如果使用“this”里面的jquery调用ajax。我想引用我的“聊天”对象,但我认为由于将它包含在jquery ajax函数中,它不是。

有关如何在该位置引用聊天对象的任何建议吗?

1 个答案:

答案 0 :(得分:2)

你不能这样做,因为ajax succes回调中的 this 指向jqXHR对象而不指向对象上下文。您可以将对象缓存到另一个变量并使用它。还有很多其他方法。

this.sendChatUpdate = function (msg) {
    var Chatmsg = '0';
    if (msg > 0) {
        Chatmsg = $('#chatmsg');
        var m = Chatmsg.val();
        Chatmsg.val('');
    }

    var s = $("#chatnick").val();
    var r = $("#chatto").val(), self = this; //Cache this to self.

    $.ajax({
        type: 'POST',
        url: 'Chat/ajax/Chat.php',
        data: {
            S: s,
            R: r,
            M: m
        },
        success: function (data) {
            self.ProcessChatReturn(data); //Invoke it with self
        },
        error: function (data) {
            self.ProcessChatReturn(data); //Invoke it with self
        }
    });
}

您还可以使用ajax设置的context属性。

例如:

   $.ajax({
        type: 'POST',
        url: 'Chat/ajax/Chat.php',
        data: {
            S: s,
            R: r,
            M: m
        },
        context:this, //set the context here
        success: function (data) {
            this.ProcessChatReturn(data); //Invoke it with this
        },
        error: function (data) {
            this.ProcessChatReturn(data); //Invoke it with this
        }
    });

还有其他方法可以使用Ecmascript5 function.bind$.proxy绑定回调函数引用,但在您的情况下,您可以避免这些。

请注意,函数内的上下文是指调用者的上下文,或者换句话说,函数是从调用的(除了上一个语句中提到的绑定函数) 。在你的情况下,你给ajax回调作为你的匿名func引用,它从jquery ajax对象调用,所以默认情况下上下文指向

相关问题