Javascript-使用类的正确方法

问题描述 投票:0回答:1

我编写了一个mqtt client.js,但意识到我需要该脚本的多个实例,因此将其重写为一个类。现在,我最终得到了很多“ this.foo”引用,这些变量都引用了我的变量,这让我感到奇怪,这是在javascript中使用类的正确方法吗?

这是我班级的一部分:

      this.client = mqtt.connect("mqtts://" + this.host, options); // mqtts for tls connection

      // client event handling
      this.client.on("connect", () => {
        log.write("LOG_INFO", "PubClient connected to Broker: " + this.host + ":" + this.settings.port);
        this.client.publish("client/publisher/status", "online", { qos: 1, retain: true });
        this.clientToSocket.pubConnect(true);
      });
      this.client.on("close", () => {
        //log.write("LOG_INFO", "PubClient close");
      });
      this.client.on("disconnect", (packet) => {
        log.write("LOG_INFO", "PubClient disconnected. Reasoncode: " + packet.reasoncode);

      });
      this.client.on("offline", () => {
        log.write("LOG_INFO", "PubClient offline");
        this.clientToSocket.pubConnect(false);
      });
      this.client.on("error", (err) => {
        //log.write("LOG_ERR", "PubClient Error: " + err.message);
      });
      this.client.on("packetreceive", (packet) => {
        //log.write("LOG_INFO", "PubClient packet received: " + packet.cmd);
      });
    }
  }

  publish(topic, qos, msg) {
    if(this.client !== undefined) {
      this.client.publish(topic, msg, { qos: parseInt(qos), retain: true });
      //log.write("LOG_INFO", "Publishing Message with: topic: " + topic + " payload: " + msg);
    } else {
      log.write("LOG_ERR", "Error: Publish not possible because client undefined");
    }
  }

  close() {
    if(this.client !== undefined) {
      this.client.end();
      log.write("LOG_INFO", "PubClient closing");
    }
  }
}
javascript class this
1个回答
0
投票

您可以使用局部变量来简化它。完成工作后,可以分配给它。

class Client {
  constructor() {
    const client = mqtt.connect("mqtts://" + host, options); // mqtts for tls connection
    client.on("connect", () => {
      log.write(
        "LOG_INFO",
        "PubClient connected to Broker: " + host + ":" + settings.port
      );
      client.publish("client/publisher/status", "online", {
        qos: 1,
        retain: true,
      });
      clientToSocket.pubConnect(true);
    });
    client.on("close", () => {
      //log.write("LOG_INFO", "PubClient close");
    });
    client.on("disconnect", (packet) => {
      log.write(
        "LOG_INFO",
        "PubClient disconnected. Reasoncode: " + packet.reasoncode
      );
    });
    this.client = client;
  }
  getClient() {
    return this.client;
  }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.