[英]How can I call a method from itself inside a class?
我目前正在實施一個 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 中使用過類,所以我有點困惑。 也許有人可以給我一個提示?
存在三個問題:
.
,例如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);
};
}
}
我找到了解決方案。 因為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);
};
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.