我目前正在实现WebSocket。因为我想在连接关闭时重新连接,所以我实现了一个connect()
函数,并试图从自身的close事件中调用它,但不幸的是它不起作用:
class WebSocket {
constructor( options = {} ) {
this.url = "ws://localhost:8181";
this.connect();
}
connect() {
let ws = new WebSocket( this.url );
ws.onclose = function ( event ) {
console.log( `WebSocket connection to ${ this.url } failed: ${ event.reason }` );
setTimeout( function () {
connect();
}, 5000 );
};
}
}
抛出的错误是:
Uncaught ReferenceError: connect is not defined
我从来没有使用过JavaScript中的类,所以有点困惑。也许有人可以给我提示吗?
答案 0 :(得分:1)
存在三个问题:
.
,例如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);
};
}
}
答案 1 :(得分:0)
我找到了解决方案。因为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);
};
}
}