2017-07-25 48 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

你應該用一份豐厚的箭頭功能的回調以獲取正確的上下文:

() => {} 
相關問題