如何创建一个自动重新连接的 webSocket 类扩展了 JavaScript 中的 WebSocket



我们可以有一个函数来实现重新连接。我知道可以只修改关闭功能,例如。

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);
  }
}

我收到错误:

解析错误:赋值表达式中的左侧无效

如何解决?

您不能重新分配this,您只能从中读取,因此它在表达式的左侧无效。

如果需要重新创建套接字,请使用组合,而不是继承:

 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();
      };
   }
 }

最新更新