我尝试在回调中调用某个函数,并使用类上下文(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