如何在类内部从自身调用方法?

时间:2020-03-27 21:49:57

标签: javascript 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中的类,所以有点困惑。也许有人可以给我提示吗?

2 个答案:

答案 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);
        };
    }
}