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 # has no method 'ProcessChatReturn'”
我认为这是因为如果在 jquery ajax 调用中使用“this”。我想引用我的“聊天”对象,但我认为由于将它包含在 jquery ajax 函数中,所以它不是。
关于如何在那个位置引用我的聊天对象有什么建议吗?
最佳答案
你不能那样做,因为 this 在 ajax 内部成功回调指向 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 绑定(bind)回调函数引用 function.bind或 $.proxy ,但在您的情况下,您可以避免这些。
请注意,函数内的上下文是指调用者的上下文,或者换句话说,函数是从调用的地方(除了最后声明中提到的绑定(bind)函数) .在你的例子中,你给了 ajax 一个回调作为你的匿名 func 引用,它是从 jquery ajax 对象调用的,所以默认情况下上下文指向那个
关于javascript - 类中的jquery函数混淆了this关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19329381/