簡體   English   中英

如何在類內從自身調用方法?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM