私はチャットクラスにupdateChatとsendChatという2つのメソッドがあります。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は未定義です。 しかし、正しい状態を得るために部屋番号を渡す必要があります(状態は単にチャットルームのテキストファイルの行数です)。
私はそれが可変スコープやオブジェクトのコンテキストで呼び出されないメソッドの問題だと思います。
など、私は、オブジェクトの非常に大量に作成するために期待していない限り、私はコンストラクタ関数、
new
、prototype
を気にしないので、便利かつ有用です() 'も同様にうまくいくでしょう。 – casablanca@casablanca - +1 - yupも真ですが、 –
を含めて更新させていただきます。ありがとう、ニック(とカサブランカ)。それが私の問題を解決しました。もし私が数時間前にそれを試してみたら、 :-( – user478419