如何创建自动重新连接webSocket类在JavaScript中扩展webSocket
我们可以使用一个函数来实现重新连接。我知道你可以修改关闭功能,例如如何创建自动重新连接webSocket类在JavaScript中扩展webSocket,javascript,Javascript,我们可以使用一个函数来实现重新连接。我知道你可以修改关闭功能,例如 let ws = new WebSocket(uri); ws.onclose = () => { ws = new WebSocket(uri); } 但是如果我想使用一个类呢 class AutoWebSocket extends WebSocket { constructor(uri, protocols) { super(uri, protocols); } onclose() {
let ws = new WebSocket(uri);
ws.onclose = () => {
ws = new WebSocket(uri);
}
但是如果我想使用一个类呢
class AutoWebSocket extends WebSocket {
constructor(uri, protocols) {
super(uri, protocols);
}
onclose() {
this = new AutoWebSocket(uri, protocols);
}
}
我犯了以下错误:
分析错误:赋值表达式中的左侧无效
如何解决此问题?您无法重新分配
此
,您只能从中读取,因此它在表达式的左侧无效
如果需要重新创建套接字,请使用组合,而不是继承:
class AuoWebSocket {
constructor(uri, protocols) {
this.uri = uri; this.protocols = protocols;
this.init();
}
init() {
this.socket = new WebSocket(uri, protocols);
this.socket.onerror = () => {
this.init();
};
}
}