简体   繁体   English

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

[英]How can I call a method from itself inside a class?

I'm currently implementing a WebSocket.我目前正在实施一个 WebSocket。 Because I want to reconnect when the connection get's closed, I've implemented a connect() function and tried to call it inside the close event from itself but unfortunately it's not working:因为我想在连接关闭时重新连接,所以我实现了一个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 );
        };
    }
} 

The thrown error is:抛出的错误是:

Uncaught ReferenceError: connect is not defined

I've never worked with classes in JavaScript so I'm a bit confused.我从来没有在 JavaScript 中使用过类,所以我有点困惑。 Maybe someone can give me a hint?也许有人可以给我一个提示?

There are three issues:存在三个问题:

  • To reference a property of an object, use .要引用对象的属性,请使用. , eg obj.prop . ,例如obj.prop Here, the object on which a property you want to reference is the instance, this .在这里,您要引用的属性的对象是实例this
  • You need to make sure this refers to the class instance inside the setTimeout , so use arrow functions您需要确保this指的是setTimeout的类实例,因此请使用箭头函数
  • The WebSocket class name clashes with the lexically scoped globalThis.Websocket property - name your class something else: 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);
    };
  }
}

I've found the solution.我找到了解决方案。 Because this refers to ws.onclose , I need to safe this instantly at the top of my function:因为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