user824624
user824624

Reputation: 8056

inherited class can not use the variable defined in the base class in node.js ES6 styled class ?

I am using ES6 syntax style to make the inheritance class in node.js, there is two classes, in which the base class is to build a mqtt client, and the inherited class is to extend the base class.

However, the problem is the inherited class can not use the variable defined in the base class.

For example, in my base class, there is a public variable called : this.mqtt_client, when I tried to use this variable in the inherited class, it always gives a undefined issue

My base class is as followed

var mqtt = require('mqtt'),
    EventEmitter = require('events').EventEmitter;

class MQTTBaseClass extends EventEmitter{

    constructor( option) {
        super();
        this.mqtt_client = null;
        this.uri = option.uri;
        this.mqttOptions.clientId = option.clientId;
    }

    init(uri, mqttOptions){
        this.mqtt_client = mqtt.connect( uri , mqttOptions ); 
        this.mqtt_client.on('connect', onConnectionSuccess);
        this.mqtt_client.on('error',onConnectionError);
        this.mqtt_client.on('message',onMessageReceived);
        ............
     }
}




class MQTTClass2 extends MQTTBaseClass{

    constructor(option) {
        super(option);
        var self  = this;
        var interval = setInterval(
            function() {
                    self.mqttClient.publish('dddd' , 'ddd' , { retain: false  },function(err){

                    })

        }, 5000);
  }
   ..............
}

Upvotes: 0

Views: 173

Answers (2)

displaynamevalue
displaynamevalue

Reputation: 138

I've made the assumption that the base class init function is being called that defines this.mqtt_client.

The issue appears to be a misspelling, you are using self.mqttClient where you should be using self.mqtt_client.

As a side note you should attempt to use a common variable naming scheme to avoid issues like this in the future: most Javascript code is written using camel case, but there is no rule against using underscores. The important thing is to be consistent.

Upvotes: 1

SLaks
SLaks

Reputation: 887275

The error is completely correct; mqttClient is undefined.

The unrelated mqtt_client field from the base class doesn't change anything.

Upvotes: 1

Related Questions