Reputation: 11
I am trying to add class C to the prototype chain of class B
class A {
constructor() {
this.a = 'a';
}
}
class B extends A {
constructor() {
super();
this.b = 'b';
}
}
class C extends A {
constructor() {
super();
this.c = 'c';
}
}
Object.setPrototypeOf(B.prototype, C.prototype);
var a = new A();
var b = new B();
console.log(b instanceof C);
console.log(b instanceof A);
console.log(b.c);
The problem with the code is that super()
call in the constructor of class B does not call the constructor of class C so the property c doesn't get added to the object. What am i doing wrong here?
Upvotes: 1
Views: 178
Reputation: 138277
super
in the constructor is based on the classes prototype (not the classes prototype property's prototype):
Object.setPrototypeOf(B.prototype, C.prototype);
Object.setPrototypeOf(B, C);
That way you also get proper static method inheritance.
Upvotes: 5