以下代码生成错误 TypeError: this.SetValue is not a function
.
class FlightData {
constructor(app)
{
this.app = app;
this.websocket = new WebSocket('ws://'+window.location.hostname+':20225/flight_data');
this.websocket.addEventListener('message', this.HandleSocketMessage);
}
SetValue(name, value)
{
console.log(name + ": " + value);
}
HandleSocketMessage(e)
{
this.SetValue("name", "value");
}
}
如果我执行以下操作,它就会起作用。然而,我试图避免在我的代码中出现闭包(即使这里的闭包是无害的):
this.websocket.addEventListener('message', e => {
this.SetValue("name", "value");
});
有人可以解释为什么顶部的代码不起作用以及我需要做什么才能使它起作用吗?
最佳答案
理解起来有点棘手,但你需要将当前上下文绑定(bind)到回调函数。否则,调用的上下文是回调自己的。
this.websocket.addEventListener('message', this.HandleSocketMessage.bind(this) )
关于javascript - 为什么从另一个方法调用方法时会得到 "TypeError: this.X is not a function"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60092235/