我正在轮询数据库。 请参阅下面代码中的“<--------------”。
这有效:
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)
}
当我使用回调函数调用该函数时,我使用“this”,但显然,它没有引用同一个对象。我在这里很困惑。
如何正确发送回调函数作为参数?
最佳答案
使用对象的方法作为回调参数时添加.bind(this)
。
所以你在poll
中的代码应该是
this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse.bind(this))
<小时/>
关于javascript - 带有 xmlhttp 的通用回调函数如何在 "this"更改时发送对函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611063/