I'm currently implementing a WebSocket. Because I want to reconnect when the connection get's closed, I've implemented a connect()
function and tried to call it inside the close event from itself but unfortunately it's not working:
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 );
};
}
}
The thrown error is:
Uncaught ReferenceError: connect is not defined
I've never worked with classes in JavaScript so I'm a bit confused. Maybe someone can give me a hint?
There are three issues:
.
, eg obj.prop
. Here, the object on which a property you want to reference is the instance, this
.this
refers to the class instance inside the setTimeout
, so use arrow functionsWebSocket
class name clashes with the lexically scoped globalThis.Websocket
property - name your class something else: 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);
};
}
}
I've found the solution. Because this
refers to ws.onclose
, I need to safe this instantly at the top of my function:
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);
};
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.