2 回答

TA貢獻1799條經(jīng)驗 獲得超6個贊
存在三個問題:
要引用對象的屬性,請使用
.
,例如obj.prop
。在這里,您要在其上引用屬性的對象是實例,this
。您需要確保
this
引用內(nèi)部的類實例setTimeout
,因此使用箭頭函數(shù)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條經(jīng)驗 獲得超6個贊
我找到了解決方案。因為this引用ws.onclose,我需要在我的函數(shù)頂部立即保護它:
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);
};
}
}
添加回答
舉報