I am using a parent class in my app to provide some basic functionality to its children. It looks roughly like this:
class Base {
constructor(stream) {
stream.subscribe(this.onData)
}
onData(data) {
throw new Error('"onData" method must be implemented')
}
}
class Child extends Base {
onData(data) {
// do stuff...
}
}
That works fine and when I instantiate the Child
, Base
passes Child.onData
to the stream
The only problem is scope. In Child.onData
I make a heavy use of other methods defined in child via this
keyword. So when I pass this function as a callback to the stream
, everything breaks. The evident solution is this:
class Base {
constructor(stream) {
stream.subscribe(this.onData)
}
onData = (data) => {
throw new Error('"onData" method must be implemented')
}
}
class Child extends Base {
onData = (data) => {
// do stuff...
}
}
That does solve problems with scope, but now the function that is being passed to the stream
is always Base.onData
which throws errors. Generally, I could do something like passing the Child.onData
to Base
constructor. That would work, but what I would like to find is a more elegant solution to this, if it exists