[英]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.