代码之家  ›  专栏  ›  技术社区  ›  lode

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

  •  0
  • lode  · 技术社区  · 6 年前

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

    这项工作:

    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作为参数正确发送?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Gabriele Petrioli    6 年前

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

    所以你的代码在里面 poll 应该是

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

    看见 Function.prototype.bind()