Reputation: 6968
When using ECMAScript 6 and classes, is it possible to call the super class method from an extending class method after an async call has completed?
Here is an abstract of the question in code:
class Foo {
constructor () {
}
myMethod (data) {
console.log('Data was: ', data);
}
}
class Bar extends Foo {
constructor () {
super();
}
myMethod () {
database.getDataForId('wth4308g40giemwfo', function (err, data) {
super.myMethod(data);
});
}
}
Using the above class Foo.myMethod() will result in an error because super no longer refers to the superclass of Foo and is undefined inside the callback.
I have tried to keep a reference to super before the callback and use that reference in the callback after it completes but that doesn't seem to work e.g.:
myMethod () {
var mySuper = super;
database.getDataForId('wth4308g40giemwfo', function (err, data) {
mySuper.myMethod(data);
});
}
Is it possible?
Upvotes: 3
Views: 923
Reputation: 78545
Arrow functions will preserve all lexical references, not just this
, so you can use one to access super
too:
myMethod () {
database.getDataForId('wth4308g40giemwfo', (err, data) => {
super.myMethod(data);
});
}
Upvotes: 6
Reputation: 51861
You cannot hold reference to super
but you can to the function:
myMethod () {
var myMethod = super.myMethod;
var self = this;
database.getDataForId('wth4308g40giemwfo', function (err, data) {
myMethod.call(self, data);
});
}
Upvotes: 2