javascript - 带有 xmlhttp 的通用回调函数如何在 "this"更改时发送对函数的引用

标签 javascript callback xmlhttprequest this

我正在轮询数据库。 请参阅下面代码中的“<--------------”。

这有效:

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))
<小时/>

参见Function.prototype.bind()

关于javascript - 带有 xmlhttp 的通用回调函数如何在 "this"更改时发送对函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611063/

相关文章:

javascript - ReactJs 组件显示旧数据(甚至不是列表)

node.js - 惯用的 Node 错误处理

javascript - 使用 Classie.js 进行回调

javascript - XMLHTTPRequest 请求打开天气返回状态 0

javascript - ajax responseText 显示为文本,而不是 html

javascript - 反转数组后,空槽变为非空

javascript - 使用 handsontable 强制卡住列行调整大小

javascript - 回调函数中的 for 循环中的回调函数

jquery - 使用 jquery 访问 Limesurvey API - 错误 631 : failed to parse request

javascript - JS 提升如何与 block 语句一起使用?