I have 3 classes:
class A{
DoStuff(){
return "Called from A";
}
}
class B extends A {
constructor(){
super();
var baseDoStuff = super.DoStuff;
this.DoStuff = function(){
return baseDoStuff() + " and Called from B";
}
}
}
class C extends B {
constructor(){
super();
var baseDoStufffff = super.DoStuff;
this.DoStuff = function(){
return baseDoStufffff() + " and Called from C";
}
}
}
I expected class C's DoStuff() to call B's DoStuff() (which in turn would call A's).
However calling DoStuff() on C only returns "Called from A and Called from C". What am I doing wrong here? Shouldn't this call B's method too?
A working example of this can be found here:
Example
Whenever you need to use super
Use class methods instead of class members:
class A{
DoStuff(){
return "Called from A";
}
}
class B extends A {
constructor(){
super();
}
DoStuff (){
return super.DoStuff() + " and Called from B";
}
}
class C extends B {
constructor(){
super();
}
DoStuff(){
return super.DoStuff() + " and Called from C";
}
}
var c = new C();
console.log(c.DoStuff());
Try it (prints Called from A and Called from B and Called from C)
This is because super
translates to .prototype
i.e. super.DoStuff()
becomes _super.prototype.DoStuff()
and the only things available on .prototype
are class methods.
More: http://basarat.github.io/TypeScriptDeepDive/#/super
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With