我有两种方法的聊天类:updateChat和sendChat。jquery变量范围问题
//chat.js
var state;
var room;
function Chat (theRoom) {
this.update = updateChat;
this.send = sendChat;
this.room = theRoom;
}
function updateChat(){
alert('ROOM: '+this.room);
$.ajax({
type: "POST",
url: "/chat/process.php",
data: {
'function': 'update',
'state': state,
'room': this.room
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
}
}
if(data.state)
state = data.state;
}
});
}
}
//send the message
function sendChat(message, nickname)
{
alert('A'+state); //20
//XXX
updateChat();
alert('B'+state); //20
$.ajax({
type: "POST",
url: "/live-event/chat/process.php",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'room': this.room
},
dataType: "json",
success: function(data){
alert('C'+state); //wrong!: 2 //it should be 20!
//XXX
updateChat();
alert('D'+state); //21
},
});
}
聊天对象的构造:
var chat = new Chat(4); //4 = the number of the chat room
chat.send('test', 'tester');
我的问题是该方法需要在标有XXX的位置。 在updateChat()方法中,如果我调用updateChat方法,this.room不确定。 但我需要通过房间号码以获得正确的状态(状态只是聊天室文本文件中的行数)。
我认为这是一个变量作用域的问题,或者在对象上下文中没有调用方法。
在这种情况下麻烦了,`this.update ()`会工作得很好。 – casablanca 2010-11-26 23:21:08