我嘗試在回調中調用某個函數,並使用類上下文(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)
}
你試過'callb.bind(個體經營)(xhttp。響應)'?即。在調用函數之前進行綁定。 – Halcyon