2017-07-25 49 views
0

我尝试在回调中调用某个函数,并使用类上下文(this)执行某些操作。但是在调用回调函数时,它没有任何上下文。 this未定义。我用bind(self)尝试了一些东西,但没有解决。在回调中获取正确的上下文(this)

export class AppComponent { 
    connect(call,callb){ 
      var self=this 
      var xhttp = new XMLHttpRequest(); 
      xhttp.responseType=responseType 
      xhttp.open("GET", "http://localhost:3000/"+call, true); 
      xhttp.onreadystatechange = function(){ 
       if (xhttp.readyState == 4 && xhttp.status == 200) 
       { 
        callb(xhttp.response).bind(self);     
       } 
      }; 
      xhttp.send(null) 
    } 


    buildXML(response){ 
      console.log(this) //prints undefined, should print AppComponent or something 
    } 

    this.connect("someCall",this.buildXML) 
} 
+1

你试过'callb.bind(个体经营)(xhttp。响应)'?即。在调用函数之前进行绑定。 – Halcyon

回答

0

您需要bind()函数上下文,然后调用它。

callb.bind(self)(xhttp.response); 

代替

callb(xhttp.response).bind(self); 
+1

绝对正确......非常感谢!有时候真的很简单;-) – Florian

2

你应该用一份丰厚的箭头功能的回调以获取正确的上下文:

() => {} 
相关问题