我正在轮询数据库。
请参阅下面代码中的“<------------”。
这项工作:
class MultiplayerGame{
...
...
callPhpWithAjax(url){
var xmlhttp = new XMLHttpRequest();
var instance = this;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
instance.pollResponse(this.responseText); <-----------works, pollResponse is called and I can access the object with "this"
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
poll(){
var url = "myurl.com"
this.callPhpWithAjax(url);
}
pollResponse(response){
this.variable = response;
}
}
当我尝试将其实现得更通用一些时,它不起作用:
class MultiplayerGame{
...
callPhpWithAjaxGenericNOTWORKING(url,callbackfunction){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callbackfunction(this.responseText); <----------callbackfunction not calling what I wanted.
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
poll(){
var url = "myurl.com"
this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse); <--------------- it seems like this.pollResponse is not ok. I don't know how to do it.
}
pollResponse(response){
this.variable = response; <----- this.variable is undefined. (this is not the class instance i was hoping)
}
当我用callbackfunction调用函数时,我使用“this”,但显然,它并不引用同一个对象。我在这里感到困惑。
如何将callbackfunction作为参数正确发送?