2 回答
TA贡献1799条经验 获得超6个赞
存在三个问题:
要引用对象的属性,请使用
.
,例如obj.prop
。在这里,您要在其上引用属性的对象是实例,this
。您需要确保
this
引用内部的类实例setTimeout
,因此使用箭头函数WebSocket
类名与词法范围属性冲突globalThis.Websocket
- 将您的类命名为其他名称:
class Connector {
constructor(options = {}) {
this.url = "ws://localhost:8181";
this.connect();
}
connect() {
const ws = new WebSocket(this.url);
ws.onclose = (event) => {
console.log(`WebSocket connection to ${ this.url } failed: ${ event.reason }`);
setTimeout(() => {
this.connect();
}, 5000);
};
}
}
TA贡献1998条经验 获得超6个赞
我找到了解决方案。因为this引用ws.onclose,我需要在我的函数顶部立即保护它:
class Connector {
constructor(options = {}) {
this.url = "ws://localhost:8181";
this.connect();
}
connect() {
const ws = new WebSocket(this.url),
self = this;
ws.onclose = (event) => {
console.log(`WebSocket connection to ${ this.url } failed: ${ event.reason }`);
setTimeout(() => {
self.connect();
}, 5000);
};
}
}
添加回答
举报