I got a sensor class and a class which extends it. The constructors of both classes use async operations.
Base class:
/**
* Basic sensor class
*/
class Sensor {
/**
* Constructor function
* @param {object} options - sensor options
* @param {*} callback - fn(err)
*/
constructor(options, callback) {
...
callback(null);
Version A (fails): Extended class, calling this in super's callback:
ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
/**
* Mock of the Chirp water level sensor.
*/
class ChirpSensorMock extends SensorMock {
/**
* Constructor function
* @param {object} options - sensor options
* @param {*} callback - fn(err)
*/
constructor(options, callback) {
super(options, (err) => {
if (err) { return callback(err); }
async.eachSeries(this.detectors,
Version B (works, but gives eslint error):
Missed superclass's construction invocation
constructor(options, callback) {
async.series([
(next) => super(options, next),
(next) => {
async.eachSeries(this.detectors,
Is there a way with using callbacks (and avoiding async/await
) to call super
and use this
in the callback? Or should I just ignore the eslint error, e.g. with // eslint-disable-next-line constructor-super
You can try binding this in Sensor to your callback which will be the this
value of callback(Will not work in arrow function) of any class that extends Sensor
class Sensor {
/**
* Constructor function
* @param {object} options - sensor options
* @param {*} callback - fn(err)
*/
constructor(options, callback) {
...
callback.call(this,null);
}
}
class ExtendSensor extends Sensor{
constructor(){
super(option, function(v){
console.log(v, this) //v == null, this == ExtendSensor{}
});
}
}