[英]javascript es6 class prototype chain modify
I am trying to add class C to the prototype chain of class B 我正在尝试将C类添加到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(bc);
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. 代码的问题在于,在类B的构造函数中调用
super()
不会调用类C的构造函数,因此不会将属性c添加到该对象中。 What am i doing wrong here? 我在这里做错了什么?
super
in the constructor is based on the classes prototype (not the classes prototype property's prototype): 构造函数中的
super
基于类原型(而不是classes prototype属性的原型):
Object.setPrototypeOf(B.prototype, C.prototype);
Object.setPrototypeOf(B, C);
That way you also get proper static method inheritance. 这样,您还可以获得适当的静态方法继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.