[英]Get right context(this) in callback
I try to call a function in a callback and do something with the class context(this). 我尝试在回调中调用函数,并使用类context(this)做一些操作。 But when calling the callback function, it doesn't have any context.
但是当调用回调函数时,它没有任何上下文。
this
is undefined. this
是未定义的。 I tried a few things with bind(self)
but didn't work out. 我用
bind(self)
尝试了一些东西,但是没有解决。
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)
}
您应该使用粗箭头函数作为回调以获取正确的上下文:
() => {}
You need to bind()
the function context, then invoke it. 您需要
bind()
函数上下文,然后调用它。
callb.bind(self)(xhttp.response);
instead of 代替
callb(xhttp.response).bind(self);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.