You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class A {
}
class B extends A {
}
class C extends B {
}
new A(); // ok
new B(); // ok
new C(); // stack overflow
Why? Because there's a default constructor that calls the constructor on the class that's been extended. That's in itself is fine.
The issue is that this is always set to the instance of C, so when the default constructor in B searches for the default constructor on the class extended by B, it always points to B's constructor instead.
It's an issue on any function in an extended class that uses super. I guess we might need to store another superThis variable that points to 'this' for the currently executing function.
The text was updated successfully, but these errors were encountered:
One workaround is to call the base class constructor explicitly:
class A { constructor() { this.foo = 42; } }
class B extends A { constructor() { A.call(this); } }
class C extends B { constructor() { B.call(this); } }
print(new C().foo); // prints 42
(Note that although this code works on Espruino, it isn't valid ES6 since it doesn't call super())
class Being {
constructor(theLabel) {
this.label = theLabel;
}
name() {
return this.label;
}
}
class Animal extends Being {
constructor(theLabel) {
super(theLabel);
}
}
class Dog extends Animal {
constructor(theLabel) {
super(theLabel);
}
}
class Cat extends Animal {
constructor(theLabel) {
super(theLabel);
}
}
const c = new Cat("Felix");
const d = new Dog("Fido");
console.log("Name:" + c.name());
Before, we were adding default constructor code of if(this.__proto__.__proto__.constructor)this.__proto__.__proto__.constructor.apply(this,arguments) to the constructor if it wasn't specified, and I figured I could do what @nebbishhacker had done above and explicitly reference the extended class (which works!) and fixes the original issue.
However super isn't so easy - I'm looking into it now
Why? Because there's a default constructor that calls the constructor on the class that's been extended. That's in itself is fine.
The issue is that
this
is always set to the instance ofC
, so when the default constructor inB
searches for the default constructor on the class extended byB
, it always points to B's constructor instead.It's an issue on any function in an extended class that uses
super
. I guess we might need to store anothersuperThis
variable that points to 'this' for the currently executing function.The text was updated successfully, but these errors were encountered: