使用xmlhttp的泛型回调函数当“this”发生变化时如何发送对函数的引用

时间:2017-12-02 18:21:45

标签: 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”,但显然,它不引用同一个对象。我在这里很困惑。

如何正确地将回调函数作为参数发送?

1 个答案:

答案 0 :(得分:1)

使用对象的方法作为回调参数时添加.bind(this)

因此poll中的代码应为

this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse.bind(this))

请参阅Function.prototype.bind()